您的位置:首页 > 其它

括号匹配

2015-07-25 17:29 260 查看


括号配对问题

时间限制:3000 ms | 内存限制:65535 KB
难度:3

描述现在,有一行括号序列,请你检查这行括号是否配对。

输入第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])


样例输出
No
No
Yes


#include<stdio.h>
#include<string.h>
int main(void)
{
int T,i;
scanf("%d",&T);
char str[105],ch[105];
while(T--)
{
memset(ch,0,sizeof(ch)); //初始化
memset(str,0,sizeof(str));
scanf("%s",str);
int top=0;
for(i=0;i<strlen(str);i++)
{
if(str[i]=='['||str[i]=='('||str[i]=='{'||str[i]=='<')
{
ch[top++]=str[i]; //入栈
}
else
{
if(ch[top-1]=='['&&str[i]==']'||ch[top-1]=='('&&str[i]==')'||ch[top-1]=='<'&&str[i]=='>'||ch[top-1]=='{'&&str[i]=='}')
{
top--;
}
else
{
printf("No\n");
break;
}
}
}
if(top==0&&(i==strlen(str)))
printf("Yes\n");
}
return 0;
}


#include <stdio.h>
int main()
{
int i;
scanf("%d",&i);
while(i--)
{
char s[10003];
int top = -1;//为空
int k = 0;
scanf("%s",s);
for(;s[k]!=0;k++)
{
if(s[top]=='('&&s[k]==')'||s[top]=='['&&s[k]==']')
{
top--;
}
else
{
top++;
s[top] = s[k];
}
}
if(top==-1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define Maxsize 11000
struct Node{
char data;
Node *next;
};
Node *top=NULL;
char Stack_getTop()
{
//printf("top\n");
if(top->next!=NULL)
return top->next->data;
else return '0';
}
void Stack_Pop()
{
//printf("pop\n");
Node* del=top->next;
if(del!=NULL)
{
top->next=del->next;
free(del);
}
}
void Stack_Push(char data)
{
//printf("push\n");
Node* one=(Node *)malloc(sizeof(Node));
one->data=data;
one->next=top->next;
top->next=one;
}
void Stack_DelAll()
{
//printf("del\n");
while(Stack_getTop()!='0')
{
Stack_Pop();
}
}
char ch[Maxsize];
int main()
{
int N;
int i;
scanf("%d",&N);
getchar();
top=(Node *)malloc(sizeof(Node));
top->next=NULL;
while(N--)
{
gets(ch);
int len=strlen(ch);
if(len%2==1)
{
printf("No\n");
continue;
}
for(i=0;i<len;i++)
{
if(ch[i]=='['||ch[i]=='(')
{
Stack_Push(ch[i]);
}
else
{
if(Stack_getTop()=='['&&ch[i]==']'||Stack_getTop()=='('&&ch[i]==')')
{
Stack_Pop();
}
else break;
}
}

if(i==len)
printf("Yes\n");
else printf("No\n");
Stack_DelAll();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: