【LeetCode从零单排】No20.ValidParentheses
生活随笔
收集整理的这篇文章主要介绍了
【LeetCode从零单排】No20.ValidParentheses
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目
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.
这道题比较经典了,就是有点像编译器判断代码符号是否符合规则,是堆栈的一个简单应用。当遇到"{","[","("的时候入栈,如果遇到这些符号的另一半,则取栈顶比较,如果是一对就继续,不然返回false。
代码
public class Solution {public boolean isValid(String s) {if(s.length()==0) return true;int len=s.length();char[] symbolFirst={'(','{','['};char[] symbolSecond={')','}',']'};char strChar[]=s.toCharArray(); Stack sym=new Stack();for(int i=0;i<len;i++){for(int j=0;j<symbolFirst.length;j++){if(strChar[i]==symbolFirst[j]){if(len==1){return false;}sym.push(strChar[i]);} }for(int k=0;k<symbolSecond.length;k++){if(strChar[i]==symbolSecond[k]){if(sym.isEmpty()){return false;}else{if(!sym.peek().equals(symbolFirst[k])){return false; }else{sym.pop();}}}}}if(sym.isEmpty()){return true;}else{return false;} } }代码下载:https://github.com/jimenbian/GarvinLeetCode
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
总结
以上是生活随笔为你收集整理的【LeetCode从零单排】No20.ValidParentheses的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【LeetCode从零单排】No14.L
- 下一篇: 【LeetCode从零单排】No19.R