题目描述:
现在,有一行括号序列,请你检查这行括号是否配对。
输入描述:
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符
输出描述:
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入:
复制
3
[(])
(])
([[]()])
样例输出:
No
No
Yes
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
#define N 10001
int main(){
stack<char> sta,stb;
char str[N],a,b;
int n,;
scanf("%d",&n);
while(n--){
scanf("%s",str);
if(strlen(str)%2 != 0)
printf("No\n");
else
{
for(int j=0; j<strlen(str); j++)
{
sta.push(str[j]);
}
while(!sta.empty())
{
a = sta.top();
sta.pop();
if(!stb.empty())
{
b = stb.top();
if((a=='(') && (b==')'))
stb.pop();
else if((a=='[') && (b==']'))
stb.pop();
else
stb.push(a);
}
else
{
stb.push(a);
}
}
if(stb.empty())
printf("Yes\n");
else
{
printf("No\n");
while(!stb.empty())
stb.pop();
}
}
memset(str,'\0',sizeof(str));
}
return 0;
}
bool match(char *str)
{
int len = strlen(str);
int flag=0;
if(len%2) //长度为奇数,不能匹配
return false;
stack<char> s;
s.push(str[0]);
for(int i=1;i<len;i++)
{
char c = *(str+i);
if(c=='[' || c=='(') //左括号直接入栈
{
s.push(*(str+i));
}
else //右括弧则取栈顶元素,看是否匹配,是则出栈,否则不匹配
{
char ch = s.top();
if(c==']'&&ch=='[')
{
flag=1;
s.pop();
}
else if(c==')'&&ch=='(')
{
flag=1;
s.pop();
}
else
{
flag=0;
break;
}
}
}
if(flag && s.empty())
return true;
return false;
}