描述
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
- 3[(])(])([[]()]) 样例输出
- NoNoYes 我自己的想法:
左右两边同时遍历 当然这是错的 测试结果很奇怪
正确做法之一:
利用数组来模拟栈的过程:
#include <iostream>
#include <bits/stdc++.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char *argv[]) {
char ch[10000],s[5000];//设定栈的大小为数组长度的一半
int n,i,top=0;
cin>>n;
while(n--){
cin>>ch;//输入输出都很简洁
for(i=0;i<strlen(ch);i++){
if(ch[i]=='['||ch[i]=='(')
s[top++]=ch[i];//表示方法要着重注意,左半拉进栈
else{
if((ch[i]==')'&&s[top-1]=='(')||(ch[i]==']'&&s[top-1]=='['))
top--;//配对成功就进行出站操作
else{
cout<<"No"<<endl;
break;
}
}
}
if(strlen(ch)!=0){
if(i==strlen(ch)&&top==0)//保证全部遍历结束 不能再栈中有残余数据
cout<<"Yes"<<endl;
}
else
n++;
top=0;//保证栈顶为0
}
return 0;
}
新的完整算法:
#include <iostream>
#include <bits/stdc++.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char *argv[]) {
char ch[10000],s[5000];
int n,i,top=0;
cin>>n;
while(n--){
cin>>ch;
for(i=0;i<strlen(ch);i++){
if(ch[i]=='['||ch[i]=='(')
s[top++]=ch[i];
else{
if((ch[i]==')'&&s[top-1]=='(')||(ch[i]==']'&&s[top-1]=='['))
top--;
else{
break;//输出位置更换
}
}
}
if(strlen(ch)!=0){
if(i==strlen(ch)&&top==0)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
top=0;//没有n++
}
return 0;
}