20. Valid Parentheses
- Total Accepted: 149046
- Total Submissions: 471508
- Difficulty: Easy
- Contributors: Admin
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 class Solution {
public boolean isValid(String s) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < s.length(); i++) {
int pos = "()[]{}".indexOf(s.substring(i, i+1));
if (pos % 2 == 1) {
if (stack.isEmpty() || stack.pop() != pos-1) {
return false;
}
} else {
stack.push(pos);
}
}
return stack.isEmpty();
}
}