思路:使用一个栈存入'(' ,'{','['三个符号,碰到其他符号取出相应地符号,直到不合法的符号出现。注意,匹配的括号数目应该是一致的。
class Solution {
public:
bool isValid(string s) {
stack<char> stackStr;
int len = s.length(), count = 0;
for(int i = 0;i<len;i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
stackStr.push(s[i]);
count++;
}
else{
if(stackStr.empty())return false;
char temp = stackStr.top();
if(s[i] == ')' && temp != '(')return false;
if(s[i] == ']' && temp != '[')return false;
if(s[i] == '}' && temp != '{')return false;
stackStr.pop();
count--;
}
}
if(count>0)return false;
return true;
}
};