题解
2024-11-29 17:13:28
发布于:浙江
5阅读
0回复
0点赞
这道题比较简单,用一个贱栈
先把左括号压栈,遇到右括号就取栈顶判断就完事啦,这边我用的是STL,大家也可以用数组模拟
别问我代码不一样,是因为我读错题了呜呜呜
#include <bits/stdc++.h>
using namespace std;
string s;
bool check(char a,char b)
{
if(a==')' && b=='(') return false;
else if(a==']' && b=='[') return false;
else if(a=='}' && b=='{') return false;
return true;
}
int main() {
int t;
cin>>t;
while(t--)
{
cin>>s;
stack <char> a;
int n=s.size();
int f=1,x=0;
for(int i=0;i<n;i++)
{
char c=s[i];
if(c=='(' || c=='{' || c=='[')
{
a.push(s[i]);
x++;
}
else
{
if(a.empty() || check(c,a.top()))
{
f=0;
break;
}
a.pop();
x--;
}
}
if(f==0 || x!=0) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}
这里空空如也
有帮助,赞一个