使用栈保存前括号,遇到后括号时,弹出栈顶元素进行匹配
class Solution {
public:
bool isValid(string s) {
if (s.size()%2==1) {//奇数个符号
return false;
}
//使用栈
stack<char> sc;
for (int i=0; i<s.size(); i++) {
if (s[i]=='('||s[i]=='['||s[i]=='{') {
sc.push(s[i]);//左括号进栈
}else if(s[i]==')'){
if (!sc.empty()&&sc.top()=='(') {
sc.pop();
}else{
return false;
}
}else if(s[i]==']'){
if(!sc.empty()&&sc.top()=='['){
sc.pop();
}else{
return false;
}
}else if(s[i]=='}'){
if(!sc.empty()&&sc.top()=='{'){
sc.pop();
}else{
return false;
}
}
}
if (sc.empty()) {
return true;
}else{
return false;
}
}
};