Q:
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.
Analysis:
中规中矩,用数据结构中的栈,如果遇到左括号,则入栈;遇到右括号,在栈不为空的情况下出栈进行括号匹配判断,若不匹配直接返回false。
Code:
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='('||c=='['||c=='{'){
stack.push(c);
}else if(c==')'){
if(!stack.isEmpty()&&'('==stack.peek()){
stack.pop();
}else{
return false;
}
}else if(c==']'){
if(!stack.isEmpty()&&'['==stack.peek()){
stack.pop();
}else{
return false;
}
}else if(c=='}'){
if(!stack.isEmpty()&&'{'==stack.peek()){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
}