题目描述
给定一个只包括 '(',')','{','}','[',']'
的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
示例
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
输入: "("
输出: false
输入: "(("
输出: false
思路
用栈来实现,
- 扫描字符串,遇到左括号,将对应的右括号压入栈
- 遇到右括号就从栈顶弹出元素进行匹配,不一样返回false
- 如果栈为空,意味着只有右括号没有左括号,返回false
- 如果括号全部匹配的话,最后栈应该为空,即以栈空为是否匹配的标准,栈空则返回true,否则false。
代码
java
class Solution {
public boolean isValid(String s) {
Stack<Character> sta = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '('){
sta.push(')');
} else if (c == '[') {
sta.push(']');
} else if (c == '{') {
sta.push('}');
} else if (sta.isEmpty() || sta.pop() != c) {
return false;
}
}
return sta.isEmpty();
}
}
class Solution {
public boolean isValid(String s) {
Stack<Integer> sta = new Stack<>();
for (int i = 0; i < s.length(); i++) {
int index = "()[]{}".indexOf(s.substring(i, i+1));
if (index % 2 == 1) {
if (sta.isEmpty() || sta.pop() != index - 1) {
return false;
}
} else {
sta.push(index);
}
}
return sta.isEmpty();
}
}
python
class Solution:
def isValid(self, s: str) -> bool:
stack = []
dic = {"{":"}", "(":")", "[":"]"}
for char in s:
if char in dic.keys():
stack.append(dic[char])
elif (stack == [] or stack.pop() != char):
return False
return stack == []