括号可以互相包含,但不能参差摆放。
PY:
代码思路:
- 使用一个栈
stack
来存储左括号。 - 遍历字符串
s
,如果当前元素是左括号,则将其压入栈中。 - 如果当前元素是右括号,则从栈中弹出一个元素。如果弹出的元素与当前元素不匹配,则返回
False
。 - 遍历结束后,如果栈为空,则返回
True
,否则返回False。
class Solution:
def isValid(self, s):
# 栈,时间:n,空间:n
stack = []
dict = {"(":")", "[":"]", "{":"}"}
for str in s:
if str in dict:
stack.append(str)
elif len(stack) == 0 or dict[stack.pop()] != str:
return False
return len(stack) == 0
注意:执行 dict[stack.pop()] != str: 此语句的时候,栈顶元素也已经出站了。
C++:
#include <iostream>
#include <string>
#include <stack>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
unordered_map<char, char> dict = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
for (char& str : s) {
if (dict.count(str))
{
stack.push(str);
} else if (stack.empty() || dict[stack.top()] != str)
{
return false;
} else
{
stack.pop();
}
}
return stack.empty();
}
};