leetcode(2)-有效的括号

题目描述:

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例:

输入: "()"
输出: true

输入: "(]"
输出: false

输入: "([)]"
输出: false

代码:

function isValid(s: string): boolean {
    const map = new Map();
    map.set('{','}');
    map.set('[',']');
    map.set('(',')');
    const stack:string[] = [];
    
    for(let i of s){
        const value = map.get(i);
        if (value) {
            stack.push(value);
        }else{
            let top = stack.pop();
            if (i != top) return false
        }
    }
    if (stack.length) {
        return false
    } else {
        return true
    }
};
原文地址:https://www.cnblogs.com/helloHT/p/13908882.html