LeetCode 20. Valid Parentheses
Description
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.
“` java
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == ‘(‘) {
stack.push(‘)’);
}
else if (c == ‘{‘) {
stack.push(‘}’);
}
else if (c == ‘[‘) {
stack.push(‘]’);
}
else if (stack.isEmpty() || stack.pop() != c) {
return false;
}
}
return stack.isEmpty();
}
验证括号序列的有效性
本文介绍了一种使用栈数据结构来验证包含括号的字符串是否有效的方法。具体实现包括遍历输入字符串,并根据遇到的不同类型的左括号向栈中压入对应的右括号;当遇到右括号时,检查它是否与栈顶元素匹配。最终,如果栈为空,则说明所有括号都正确闭合。
316

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



