20 Valid Parentheses
1. Question
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.
2. Implementation
思路:查看括号匹配问题,就看相应的符号是否对称,可以直接用stack做
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
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();
}
}
3. Time & Space Complexity
时间和空间都是O(n)
Last updated
Was this helpful?