#include <unordered_map>
class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
stack<int> st;
unordered_map<char, char> hash = {{'[', ']'}, {'{', '}'}, {'(', ')'}};
for (auto &c: s) {
if (hash.count(c)) {
st.push(hash[c]);
} else {
if (st.empty() || st.top() != c) {
return false;
}
st.pop();
}
}
return st.empty();
}
};
思路:栈模拟。
* 遇到左括号,将对应的右括号压入栈。
* 遇到右括号,如果栈顶没有匹配,则返回false,否则将栈顶弹出。
最后还需要判断栈为空。

京公网安备 11010502036488号