Valid Parentheses
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.
Tips:
用stack, 看到左括号就入栈,看到右括号就出栈看能不能匹配到左括号。
Code:
public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push('(');
continue;
}
if (s.charAt(i) == '{') {
stack.push('{');
continue;
}
if (s.charAt(i) == '[') {
stack.push('[');
continue;
}
if (s.charAt(i) == ']') {
if (stack.isEmpty()) {
return false;
}
if (stack.pop() != '[') {
return false;
}
}
if (s.charAt(i) == '}') {
if (stack.isEmpty()) {
return false;
}
if (stack.pop() != '{') {
return false;
}
}
if (s.charAt(i) == ')') {
if (stack.isEmpty()) {
return false;
}
if (stack.pop() != '(') {
return false;
}
}
}
if (stack.isEmpty()) {
return true;
}
return false;
}
}