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) {
if (s == null || s.length() == 0)
return true;
LinkedList<Character> stack = new LinkedList<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
stack.push(s.charAt(i));
if (s.charAt(i) == '[')
stack.push(s.charAt(i));
if (s.charAt(i) == '{')
stack.push(s.charAt(i));
if (s.charAt(i) == ')') {
if (stack.isEmpty() || stack.pop() != '(')
return false;
}
if (s.charAt(i) == ']') {
if (stack.isEmpty() || stack.pop() != '[')
return false;
}
if (s.charAt(i) == '}') {
if (stack.isEmpty() || stack.pop() != '{')
return false;
}
}
if (stack.isEmpty())
return true;
return false;
}