[LeetCode from zero to single] now.validparentheses, leetcode
Question
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"(]"And"([)]"Are not.
This is a classic question. It is a simple application of the stack to determine whether the code symbol complies with the rules. When you encounter "{", "[", "(", ", if you encounter the other half of these symbols, compare them with the top of the stack. If they are one pair, continue, otherwise, false is returned.
Code
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; } }}
Code download: https://github.com/jimenbian/GarvinLeetCode
/********************************
* This article is from the blog "Li bogarvin"
* Reprinted please indicate the source: http://blog.csdn.net/buptgshengod
**************************************** **/