原题:
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>();
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if("({[".contains(String.valueOf(c))) {
stack.push(c);
} else {
if(!stack.isEmpty() && charMatch(stack.peek(), c)) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
private boolean charMatch(char c1, char c2) {
if(c1=='(' && c2==')')
return true;
if(c1=='{' && c2=='}')
return true;
if(c1=='[' && c2==']')
return true;
return false;
}