js判断括号的合法性

606 阅读1分钟

作者:demigodliu

链接:leetcode-cn.com/problems/va…

来源:力扣(LeetCode)

解题思路

  1. 有效括号字符串的长度,一定是偶数!
  2. 右括号前面,必须是相对应的左括号,才能抵消!
  3. 右括号前面,不是对应的左括号,那么该字符串,一定不是有效的括号!

图解

image.png

示例代码

let isValid = function(s) {
    let stack = [], length = s.length;
    if(length % 2) return false;
    for(let item of s){
        switch(item){
            case "{":
            case "[":
            case "(":
                stack.push(item);
                break;
            case "}":
                if(stack.pop() !== "{") return false;
                break;
            case "]":
                if(stack.pop() !== "[") return false;
                break;
            case ")":
                if(stack.pop() !== "(") return false;
                break;
        }
    }
    return !stack.length;
};