为什么只能对三个点? 大佬求助!
#include<bits/stdc++.h>
using namespace std;
string s;
int top=0;
string a;
int main(){
int n;
cin>>n;
for(int j=1;j<=n;j++){
cin>>s;
bool flag=true;
top=0;
for(int i=0;i<s.length();i++){
if(s[i]=='{'&&((a[top]=='{')||top==0)){
a[++top]=s[i];
}
else if(s[i]=='['&&((a[top]=='{'||a[top]=='[')||top==0)){
a[++top]=s[i];
}
else if(s[i]=='('&&((a[top]=='{'||a[top]=='['||a[top]=='(')||top==0)){
a[++top]=s[i];
}
else if(s[i]=='<'){
a[++top]=s[i];
}
else if(s[i]==')'&&a[top]=='('){
top--;
}
else if(s[i]==']'&&a[top]=='['){
top--;
}
else if(s[i]=='>'&&a[top]=='<'){
top--;
}
else if(s[i]=='}'&&a[top]=='{'){
top--;
}
else{
cout<<"NO"<<endl;
flag=false;
break;
}
}
if(top==0&&flag){
cout<<"YES"<<endl;
}
else if(flag&&top!=0){
cout<<"NO"<<endl;
}
}
return 0;
}
AC代码:
#include<iostream>
#include<cstring>
#include<cstring>
using namespace std;
bool judge(string s)
{
char st[300];
memset(st,0,sizeof(0));
int top=-1;
for(int i=0;i<s.length();i++)
{
if(s[i]=='<')st[++top]=s[i];
if(s[i]=='>'){
if(st[top]=='<')top--;
else return 0;
}
if(s[i]=='('){
if(top>-1&&st[top]=='<')return 0;
else st[++top]=s[i];
}
if(s[i]==')'){
if(st[top]=='(')top--;
else return 0;
}
if(s[i]=='['){
if(top>-1&&(st[top]=='<'||st[top]=='('))return 0;
else st[++top]=s[i];
}
if(s[i]==']'){
if(st[top]=='[')top--;
else return 0;
}
if(s[i]=='{'){
if(top>-1&&(st[top]=='<'||st[top]=='('||st[top]=='['))return 0;
else st[++top]=s[i];
}
if(s[i]=='}'){
if(st[top]=='{')top--;
else return 0;
}
}
if(top==-1)return 1;
else return 0;
}
int main()
{
int n;
cin>>n;
while(n--)
{
string s;
cin>>s;
if(judge(s))cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}