数据结构实验之栈与队列四:括号匹配

Description

 给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

 

Input

 输入数据有多组,处理到文件结束。

 

Output

 如果匹配就输出“yes”,不匹配输出“no”

 

Sample

Input 

sin(20+10)
{[}]

Output 

yes
no
 1 #include<stdio.h>
 2 
 3 int main()
 4 {
 5     char s[1000];
 6     char ss[1000];//
 7     while(gets(s))
 8     {
 9         int top = 0;//标记栈顶,每次都要重新标记
10         int i = 0;
11         while(s[i]!='\0')
12         {
13             if(s[i]=='('||s[i]=='{'||s[i]=='[')
14                 ss[top++] = s[i];//进栈
15             if(s[i]==')'||s[i]=='}'||s[i]==']')
16                 if(ss[top-1]=='('&&s[i]==')'||ss[top-1]=='['&&s[i]==']'||ss[top-1]=='{'&&s[i]=='}')//对应相等
17                     top--;//出栈
18                 else
19                     break;
20             i++;
21         }
22         if(top==0&&s[i]=='\0')//一定要保证是读到最后一直满足对应相等如果没有s[i]=='\0',那么()[这种也会是yes
23             printf("yes\n");
24         else
25             printf("no\n");
26     }
27     return 0;
28 }

 

posted @ 2020-07-26 10:53  爱写程序的机械师  阅读(134)  评论(0)    收藏  举报