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: false
题意:给出一个字符串,字符串只包括不同类型的括号,问匹配是否正确。 这个是个非常经典的 stack 题。 遇到左括号就压入栈,遇到右括号,就出栈,如果匹配不上就返回 false
代码
class Solution {
public boolean isValid(String s) {
if(s == null || s.equals("")) return true;
int i = 0;
Stack<Character> stack = new Stack<>();
while(i < s.length()) {
if(s.charAt(i) == '{' || s.charAt(i) == '[' || s.charAt(i) == '(') {
stack.push(s.charAt(i));
} else {
if(stack.isEmpty()) return false;
if(stack.peek() == '{' && s.charAt(i) == '}' || stack.peek() == '[' && s.charAt(i) == ']' ||stack.peek() == '(' && s.charAt(i) == ')' ) {
stack.pop();
}
else{
return false;
}
}
i++;
}
return stack.isEmpty();
}
}