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
stack.peek()与stack.pop()区别
相同点:大家都返回栈顶的值。
不同点:peek()不改变栈的值(不删除栈顶的值),pop()会把栈顶的值删除。
//java
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// 如果是左括号,则入栈
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
// 如果是右括号,则比较其与栈顶元素是否配对
if (stack.isEmpty()) {
return false;
}
if (ch == ')' && stack.peek() != '(') {
return false;
}
if (ch == ']' && stack.peek() != '[') {
return false;
}
if (ch == '}' && stack.peek() != '{') {
return false;
}
stack.pop();
}
}
// 最后栈为空则表示完全匹配完毕
return stack.isEmpty();
}