Valid Parentheses
Solution 1
经典的栈练习题。需要注意两个判定条件:括号类型的搭配以及方向(先右后左不能配对)。
- 时间复杂度: O ( N ) O(N) O(N), N N N为输入字符串的长度,遍历需要
- 空间复杂度: O ( N ) O(N) O(N), N N N为输入字符串的长度,栈的数据需要
class Solution {
public:
bool isValid(string s) {
stack<char> check;
map<char, int> parenthese;
parenthese['('] = -1;
parenthese[')'] = 1;
parenthese['['] = -2;
parenthese[']'] = 2;
parenthese['{'] = -3;
parenthese['}'] = 3;
for (auto c: s) {
if (!check.empty() && parenthese[check.top()] + parenthese[c] == 0 && parenthese[check.top()] < parenthese[c]) {
check.pop();
}
else {
check.push(c);
}
}
if (check.empty()) {
return true;
}
else {
return false;
}
}
};
Solution 2
Solution 1的Python实现,头一次留意到Python的列表是对应了栈的实现的。
class Solution:
def isValid(self, s: str) -> bool:
parenthese = {'(': -1, ')': 1, '[': -2, ']': 2, '{': -3, '}': 3}
check = list()
for c in s:
if len(check) > 0 and parenthese[check[-1]] + parenthese[c] == 0 and parenthese[check[-1]] < parenthese[c] :
check.pop()
else :
check.append(c)
if len(check) != 0:
return False
else:
return True