题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=2
解题思路:
比较经典的栈的应用。首先将字符串首字符入栈,然后遍历剩余的字符,根据栈顶字符和当前字符串来考虑是入栈还是出栈。当前栈顶跟当前遍历的字符不匹配时,需要入栈;若能匹配,则执行出栈操作。字符串全都遍历完的时候,若栈为空,就证明所有的括号都能匹配;否则,证明有括号不能匹配。
代码如下:
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main(){
int N;
cin>>N;//N组
char tmp[10001];//存括号字符串
for(int i=0;i<N;i++){
cin>>tmp;
stack<char> s;
s.push(tmp[0]);//字符串第一个先入栈
for(int j=1;j<strlen(tmp);j++){
if(s.empty()){
s.push(tmp[j]);
continue;
}
char tops=s.top();//取栈顶
if(tops=='('){
if(tmp[j]==')')
s.pop();
else
s.push(tmp[j]);
}
else if(tops=='['){
if(tmp[j]==']')
s.pop();
else
s.push(tmp[j]);
}
else
s.push(tmp[j]);
}
if(s.empty())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}