大家都知道算术表达式中,括号必须配对,现在任意给出一个算术表达式,判断其括号是否配对。如果配对,输出Yes
,否则输出No
。
Standard Input
含多组测试数据,输入首先是一个整数TT表示测试数据组数(0<T \leq 3000<T≤300)。随后有TT行测试数据,长度不超过10001000个字符,字符串间不含空格。
Standard Output
对应每组测试数据,输出一行结果。
Samples
Input | Output |
---|---|
2 32*(78-23)+78 32*78)-(23+78) | Yes No |
Problem ID | 649 |
Problem Title | 括号配对问题 |
Time Limit | 1000 ms |
Memory Limit | 64 MiB |
Output Limit | 64 MiB |
Source | wxiaoping - 2012 |
思路:
我们将左括号入栈,然后遇到右括号的时候判断一下是否有左括号,有的话出栈,否则标记一下。
最后栈内元素为0且没有标记才正确。
代码:
#include<iostream>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#include<string.h>
#include<queue>
#include<stack>
#include<cstdio>
using namespace std;
const int maxn=20+6;
#define mod 1000000007
#define INF 0x3f3f3f3f
int dx[]= {-1,1,0,0};
int dy[]= {0,0,-1,1};
char ch[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",ch+1);
int len=strlen(ch+1);
stack<char>s;
while(s.size())s.pop();
int flag=0;
rep(i,1,len)
{
if(ch[i]=='('||ch[i]=='[')
{
s.push(ch[i]);
}
if(ch[i]==')'||ch[i]==']')
{
if(s.size())
{
s.pop();
}else
{
flag=1;
//cout<<ch[i]<<endl;
}
}
}
if(!(flag||s.size()))
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
}
}