[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
- [leetcode javascript解题]Valid Parentheses
- LeetCode Valid Parentheses (JavaScript)
- LeetCode解题报告--Valid Parentheses
- [LeetCode] Valid Parentheses 解题报告
- [LeetCode] Valid Parentheses 解题报告
- 【LeetCode】Valid Parentheses 解题报告
- LeetCode解题-#20-Valid Parentheses
- Leetcode Valid Parentheses 解题报告
- Leetcode 20. Valid Parentheses - javascript
- [LeetCode]Longest Valid Parentheses, 解题报告
- LeetCode Longest Valid Parentheses 解题报告
- [LeetCode] Longest Valid Parentheses 解题报告
- 【LeetCode】Longest Valid Parentheses 解题报告
- [leetcode] 20. Valid Parentheses 解题报告
- [leetcode] 32. Longest Valid Parentheses 解题报告
- [Leetcode] 20. Valid Parentheses 解题报告
- [Leetcode] 32. Longest Valid Parentheses 解题报告
- leetcode解题报告20. Valid Parentheses
- svn服务器配置
- MVC5的模式构建网站(一)
- Have Fun with Numbers
- 从菜鸟到入门,掌握 Log4j
- linux系统调用和库函数调用的区别
- [leetcode javascript解题]Valid Parentheses
- MongoDB 分片的原理、搭建、应用
- 文字阴影
- 时间的尾翼
- [javax.validation]验证
- npm install -g cordova ionic太慢了
- javascript集合的交,并,补,子集,长度,新增,删除,清空等操作
- 朋友圈 个人信息 界面 下拉 头部图片视图跟随缩放变化
- STM32学习15