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 boolean isValid(String s) {
Stack<Character> stack=new Stack<Character>();
int n=s.length();
for(int i=0;i<n;i++){
if(s.charAt(i)=='(')
stack.push(')');
else if(s.charAt(i)=='[')
stack.push(']');
else if(s.charAt(i)=='{')
stack.push('}');
else{
if(!stack.isEmpty()&&stack.pop()!=s.charAt(i))
return false;
}
}
return stack.isEmpty();
}
//括号匹配问题,使用栈实现。