- 遍历字符串,如果是左括号则压到栈中,如果是右括号则检查是否与栈顶的左括号匹配,如果匹配则弹出栈顶元素。遍历完字符串,如果栈为空则说明所有括号均匹配成功
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (auto& x : s) {
if (x == '(' || x == '{' || x == '[') {
stk.emplace(x);
} else if (!stk.empty() && stk.top() == m.at(x)) {
stk.pop();
} else {
return false;
}
}
return stk.empty();
}
private:
const unordered_map<char, char> m{
{')', '('},
{'}', '{'},
{']', '['},
};
};