Java實現-有效的括號序列
阿新 • • 發佈:2019-01-31
public class Solution { /** * @param s A string * @return whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { // Write your code here if(s.length()==0){ return false; } if(s.length()%2==1){ return false; } Stack<Character> stack=new Stack<Character>(); for(int i=0;i<s.length();i++){ Character c=s.charAt(i); if(c!='('&&c!=')'&&c!='['&&c!=']'&&c!='{'&&c!='}'){ return false; } if(c=='('||c=='{'||c=='['){ stack.push(c); }else{ if(stack.isEmpty()){ return false; } if(c==')'){ if(stack.peek()!='('){ return false; }else{ stack.pop(); } }else if(c==']'){ if(stack.peek()!='['){ return false; }else{ stack.pop(); } }else{ if(stack.peek()!='{'){ return false; }else{ stack.pop(); } } } } if(!stack.isEmpty()){ return false; }else{ return true; } } }