括号配对问题
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
- 现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No Yes
来源
第一种做法: 栈
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cstdio>
using namespace std;
struct sStack
{
char sign[10010];
int top;
};
void initstack(sStack &s)//创建栈
{
s.top=-1; //初始化栈空间,-1表明栈当前为空。
}
bool isemptystack(sStack &s)//判断栈是否为空
{
return s.top==-1?1:0;
}
int pushstack(sStack &s,char c)//入栈
{
s.sign[++s.top]=c;
return 1;
}
int popstack(sStack &s)//出栈
{
if(isemptystack(s))
return 0;
s.top--;
return 1;
}
char topstack(sStack &s)//输出栈顶元素
{
if(isemptystack(s))
return 0;
return s.sign[s.top];
}
int main()
{
int N,len;
bool flag;
char str[10010];
sStack s;
scanf("%d",&N);
getchar();
while(N--)
{
flag=1;
scanf("%s",str);
len=strlen(str);
initstack(s);//将栈置空
for(int i=0;i<len;++i)
{
if(str[i]=='('||str[i]=='[')
pushstack(s,str[i]);//向堆栈顶部添加实参指定的元素
else if(str[i]==')')
{
if(isemptystack(s)||topstack(s)!='(')
flag=0;
else
popstack(s);//对应上了,删除堆栈顶部的元素
}
else if(str[i]==']')
{
if(isemptystack(s)||topstack(s)!='[')
flag=0;
else
popstack(s);
}
}
if(!isemptystack(s))//空栈
flag=0;
if(flag)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
第二种:模拟
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
char a[10005];//主要思想:不管有多少个括号,中间的或者两边的最终会配对,配对一个消除一对即可
int n,i,j;
scanf("%d",&n);
getchar();
while(n--)
{
a[0]=0;
i=1;//从数组下标为1的元素开始
a[i]=getchar();//一个字符一个字符的处理
while(a[i]!='\n')
{
if(a[i]==']' && a[i-1]=='[' || a[i]==')' && a[i-1]=='(')
i--;//如果读入的字符与前面元素相匹配,就把这两个元素消去,即i--
else
i++;//否则就存下来
a[i]=getchar();
}
if(i>1)
printf("No\n");//最后检查数组中是否存入了括号,有就是有括号不配对
else
printf("Yes\n");
}
return 0;
}
第三种:指针 难理解
#include<stdio.h>
#include<string.h>
int judge(char *p)
{
int xx,yy;
char *ptmp;
ptmp=p;//此时ptmp是一个地址,可以理解为指向testdata[0];
while(*ptmp!='\0')
{
xx=yy=0;
if(*ptmp=='(')
xx=1;
else if(*ptmp=='[')
yy=1;
else return -1;
if(xx)
{
while((*(++ptmp)!='\0')&&(xx!=0))
{
if(*ptmp=='(')
xx++;
if(*ptmp=='[')
yy++;
if(*ptmp==')')
{
xx--;
if(xx<0)//说明不配对,出现了错误情况 例如())
return -1;
}
if(*ptmp==']')
{
yy--;
if(yy<0) //(]]
return -1;
}
}
if(yy)//([)
return -1;
}
if(yy)
{
while((*(++ptmp)!='\0')&&(yy!=0))
{
if(*ptmp=='(')
xx++;
if(*ptmp=='[')
yy++;
if(*ptmp==')')
{
xx--;
if(xx<0)
return -1;
}
if(*ptmp==']'){
yy--;
if(yy<0)
return -1;
}
}
if(xx)
return -1;
}
}
return 0;
}
int main()
{
int t,res,i,j;
char testdata[10010];
scanf("%d",&t);
while(t--)
{
scanf("%s",testdata);
int x=0,y=0,len; //x是小括号数量,y是中括号数量
len=strlen(testdata);
j=0;
while(testdata[j]!='\0')//对字符串进行分析
{
switch(testdata[j])
{
case'(':x++;break;
case')':x--;break;
case'[':y++;break;
case']':y--;break;
}
j++;
}
if(x==0 && y==0)//先初步判断括号是否成对
{
res=judge(testdata);
if(res==0)
printf("Yes\n");
else
printf("No\n");
}
else
printf("No\n");
}
return 0;
}