【LeetCode從零單排】No20.ValidParentheses,leetcode
題目
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
******************************************/