[leetcode javascript解题]Valid Parentheses

来源:互联网 发布:那个软件有手机型号 编辑:程序博客网 时间:2024/06/05 07:27

leetcode 20题 Valid Parentheses 描述如下

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解题思路其实比较简单就是建立一个栈结构,储存”([{“。首先如果字符串的length为奇数,显然可以直接返回false了。
接着是优化代码。个人是很讨厌冗长的switch语句,所以用正则表达式和charCodeAt来处理了,注意到 '(', ')', '{', '}', '[' 以及 ']', 的 Unicode 编码分别为40,41,91,93,123和125。所以在判断时可以根据同样的括号类型编码值相减小于等于2的原理来判断。代码看上去就简洁了很多。
循环过程中,如果条件匹配就出栈,不匹配的话基本就意味着有多余的符号,直接返回false。如果都匹配,还要查看最终的判断条件也就是stack中是否还有元素剩余。

/** * @param {string} s * @return {boolean} */var isValid = function(s) {    if (s.length % 2 === 1 || /[\}\]\)]/.test(s[0])) {        return false;    }    var stack = [];    for (var i = 0; i < s.length; i++) {        if (/[\{\[\(]/.test(s[i])) {            stack.push(s[i]);        } else {            var len = stack.length;            if (Math.abs(stack[len - 1].charCodeAt(0) - s[i].charCodeAt(0)) <= 2) {                stack.pop();            } else {                return false;            }        }    }    if (stack.length === 0) {        return true;    } else {        return false;    }};
0 0
原创粉丝点击