括号匹配,通过用栈来存储,如果有栈顶和要输入的括号匹配,那么就将栈中的括号弹出,如果不匹配,那么将这个要输入的括号压入栈中。判断括号是不是匹配,通过判断栈是不是到最后为空,为空则说明匹配。
class Solution {
public:
bool isValid(string s) {
stack<char> temp;
temp.push(s[0]);
int cnt=1;
while((cnt<s.size())){
if(temp.empty()){temp.push(s[cnt]);cnt++;continue;}
char tt=temp.top();
if(tt=='('&&s[cnt]==')')temp.pop();
else if(tt=='{'&&s[cnt]=='}')temp.pop();
else if(tt=='['&&s[cnt]==']')temp.pop();
else temp.push(s[cnt]);
cnt++;
}
if(temp.empty())return true;
else return false;
}
};