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();
}
博客讨论了判断包含特定括号字符的字符串是否有效的问题,需满足括号类型匹配且按正确顺序闭合,空字符串也视为有效。还介绍了 stack.peek() 与 stack.pop() 的区别,二者都返回栈顶值,但 peek() 不改变栈,pop() 会删除栈顶值。
306

被折叠的 条评论
为什么被折叠?



