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

来源:互联网 发布:简谱打谱软件 编辑:程序博客网 时间:2024/06/07 00:06
Problem Description 给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。Input 输入数据有多组,处理到文件结束。 Output 如果匹配就输出“yes”,不匹配输出“no” Example Inputsin(20+10){[}]Example OutputyesnoHint  


括号匹配是数据结构栈中的典型例题,括号的匹配并不是有括号是一对就可以,要相互对应。

“{” 、 “(” 、 “[” 左括号可以随时入栈,但右括号“}” 、“)” 、“]”入栈时,要匹配上和右括号相同括号类型的左括号,这才算括号的匹配。

#include<stdio.h>struct kuohao{char st[60];int top;}s;int match(char c[]){int i=0;s.top=0;while(c[i]!='\0'){switch(c[i]){case '{':case '[':case '(':s.st[s.top]=c[i];s.top++;break;//{、[、(全部进行入栈操作case '}':if(s.top>0 && s.st[s.top-1]=='{')s.top--;elsereturn 0;break;case ']':if(s.top>0 && s.st[s.top-1]=='[')s.top--;elsereturn 0;break;case ')':if(s.top>0 && s.st[s.top-1]=='(')s.top--;elsereturn 0;break;}i++;}if(s.top==0)return 1;elsereturn 0;}char str[60];int main(){int i,j;while(gets(str)){if(match(str))printf("yes\n");elseprintf("no\n");}return 0;}


原创粉丝点击