20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
My Solutions:
用一个char stack记录。
如果char是左括号(,{,【,在stack里记录下对应的右括号),},】。
如果碰到是右括号,检查stack是否为空,如果已经为空,直接返回false。如果不为空,pop stack,检查pop出来的括号是否和char相同。
public boolean isValid(String s) {
if(s.length() % 2 == 1) return false;
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();
}
Last updated