class Solution {
public:
bool isValid(string s) {
// 创建一个字符栈,用于存储左括号
stack<char> stack;
// 创建一个哈希表,用于存储左右括号的对应关系
unordered_map<char, char> match = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
for (char c : s) {
// 如果字符是左括号,将其压入栈中
if (match.find(c)!= match.end()) {
stack.push(c);
} else {
// 如果栈为空或者当前字符与栈顶元素对应的右括号不匹配,返回 false
if (stack.empty() || match[stack.top()]!= c) {
return false;
}
// 如果匹配成功,弹出栈顶元素
stack.pop();
}
}
// 如果栈为空,说明所有括号都匹配成功,返回 true
return stack.empty();
}
};