[leedcode 20] Valid Parentheses
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.
public class Solution { public boolean isValid(String s) { //题解:需要辅助栈进行判断,时间复杂度为O(n),空间复杂度为O(n) //遇到左括号则进栈,遇到右括号时需要判断:1.栈是否为空,2.栈顶是否和此符号匹配。二者有一个条件不匹配则返回false //注意以下几个细节: //1.出栈时需要判断栈空 //2.最终返回结果需要判断栈是否为空 Stack<Character> stack=new Stack<Character>(); for(int i=0;i<s.length();i++){ char temp=s.charAt(i); if(temp=='('||temp=='{'||temp=='[') stack.push(temp); else{ if(temp==')'){ if(!stack.empty()&&(char)stack.peek()=='(') stack.pop(); else return false; } if(temp==']'){ if(!stack.empty()&&(char)stack.peek()=='[') stack.pop(); else return false; } if(temp=='}'){ if(!stack.empty()&&(char)stack.peek()=='{') stack.pop(); else return false; } } } return stack.empty(); } }