我的思路
一共四种情况,
栈空的时候遇到左括号,栈不空的时候遇到左括号。
栈空的时候遇到右括号,栈不空的时候遇到右括号。
遇到左括号无条件入栈,遇到右括号分情况出栈或直接判错。
bool isValid(string s){
stack<char> v;
for (auto x : s) {
if (x == '(' || x == '[' || x == '{') { v.push(x); continue; }
if (v.empty()) {
if (x == ')' || x == ']' || x == '}')
return false;
}else{
if (x == ')' && v.top() == '(') v.pop();
else if (x == ']' && v.top() == '[') v.pop();
else if (x == '}' && v.top() == '{') v.pop();
else return false;
}
}
return v.empty();
}
菜的真实
执行用时 : 8 ms, 在Valid Parentheses的C++提交中击败了17.41% 的用户
内存消耗 : 8.3 MB, 在Valid Parentheses的C++提交中击败了0.93% 的用户
????