class Solution {
public:
bool isValid(string s) {
stack<char> sta;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
sta.push(s[i]);
}
else if (s[i] == ')') {
if (sta.empty() || sta.top() != '(') {
return false;
}
else {
sta.pop();
}
}
else if (s[i] == ']') {
if (sta.empty() || sta.top() != '[') {
return false;
}
else {
sta.pop();
}
}
else if (s[i] == '}') {
if (sta.empty() || sta.top() != '{') {
return false;
}
else {
sta.pop();
}
}
}
if (!sta.empty()) {
return false;
}
return true;
}
};
LeetCode 20:有效的括号(Valid Parentheses)解法汇总
最新推荐文章于 2020-07-22 16:13:00 发布