用栈结构 判断最近的 括号是否对应
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
stk.push(s[i]);
else if (s[i] == ')') {
if (stk.empty() || stk.top() != '(')
return false;
stk.pop();
}
else if (s[i] == ']') {
if (stk.empty() || stk.top() != '[')
return false;
stk.pop();
}
else {
if (stk.empty() || stk.top() != '{')
return false;
stk.pop();
}
}
return stk.empty();
}
};