题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
class Solution {
public:
bool isValid(string s) {
// write code here
stack<char> comp_stack;
for (char& c : s) {
if (c == '(' || c == '{' || c == '[') {
comp_stack.push(c);
continue;
}
if(comp_stack.empty())
return false;
char top = comp_stack.top();
if (top == '(' && c == ')') {
comp_stack.pop();
continue;
}
if (top == '[' && c == ']') {
comp_stack.pop();
continue;
}
if (top == '{' && c == '}') {
comp_stack.pop();
continue;
}
return false;
}
return comp_stack.size() == 0 ? true : false;
}
};
查看7道真题和解析