题目链接:https://leetcode.cn/problems/valid-parentheses/
C++代码如下:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (auto& c : s) {
if (c == '(' || c == '{' || c == '[') {
stk.push(c);
} else {
if (stk.empty()) return false;
if (c == ')' && stk.top() != '(') return false;
else if (c == '}' && stk.top() != '{') return false;
else if (c == ']' && stk.top() != '[') return false;
stk.pop();
}
}
return stk.empty();
}
};