leetcode hot100 20.有效括号

119 阅读1分钟

练手题:

用数组模拟栈,和栈顶相匹配则相互抵消,即栈顶出栈,且当前元素不入栈,直接进入下一次循环;

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    if(len = s.length < 2) return false;

    let res = [];
    for(let char of s) {
        if (res[res.length - 1] === '(' && char === ')') { res.pop(); continue; }
        if (res[res.length - 1] === '[' && char === ']') { res.pop(); continue; }
        if (res[res.length - 1] === '{' && char === '}') { res.pop(); continue; }
        res.push(char);
    }
    return res.length === 0;
};

image.png