【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“

* 转载请标明出处:

******************************************/

找回自我,歇够了,再飞回来,继续面对自己的人生。

【LeetCode从零单排】No20.ValidParentheses

相关文章:

你感兴趣的文章:

标签云: