有效的括号[leetcode题号20]

https://leetcode.cn/problems/valid-parentheses/

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"
输出:true
1
2

示例 2:

输入:s = "()[]{}"
输出:true
1
2

示例 3:

输入:s = "(]"
输出:false
1
2
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const str = s.split('')
    let res = true;
    let arr = [];
    const dictMap = {
        ')':'(',
        ']':'[',
        '}':'{'
    }
    while(str.length > 0){
            const item = str.shift();
            if(item === '(' || item === '{' || item === '['){
                arr.push(item)
            }else{
                const data = arr.pop()
                if(dictMap[item] !== data){
                    res = false;
                    break;
                }
            }
    }
    if(res && arr.length > 0) res = false;
    return res
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28