题目地址:
Given a string s 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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
import java.util.Deque;
import java.util.LinkedList;
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
// 如果当前字母是左括号,直接入栈
if (cur == '(' || cur == '[' || cur == '{') {
stack.push(cur);
} else {
// 如果是右括号,若栈空直接返回false
if (stack.isEmpty()) {
return false;
}
// 如果栈不空且与栈顶匹配,pop栈顶;否则返回false
if (match(stack.peek(), cur)) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
private boolean match(char c1, char c2) {
if ((c1 == '(' && c2 == ')')
|| (c1 == '[' && c2 == ']'
|| (c1 == '{' && c2 == '}'))) {
return true;
}
return false;
}
}