跳到主要内容

20 有效的括号

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnbcaj/

https://leetcode.cn/problems/valid-parentheses/description/

cost: 6m34s

class Solution {
public:
bool isValid(string s) {
stack<char> mystack;
for (const char& ch : s) {
switch (ch) {
case '(':
mystack.push(')');
break;
case '[':
mystack.push(']');
break;
case '{':
mystack.push('}');
break;
case ')':
case ']':
case '}':
if (mystack.empty()) {
return false;
}
if (mystack.top() != ch) {
return false;
}
mystack.pop();
break;
default:
}
}
return mystack.empty();
}
};