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.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public class { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c : s.toCharArray()) { if(c == '(') stack.push(')'); else if (c == '[') stack.push(']'); else if(c == '{') stack.push('}'); else if(stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); } }
|
近期评论