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

来源:互联网 发布:数据表格共享平台 编辑:程序博客网 时间:2024/06/01 21:52

Problem Description

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

Input

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

Output

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

Example Input

sin(20+10)
{[}]

Example Output

yes
no

#include<iostream>#include<cstring>using namespace std;int main(){    char str[100010];    int i ,top,mat,len;    char ans[10010];    while(cin.getline(str,10010))    {        top = 0; len = strlen(str) ; mat = 1;        for(i = 0;i<len;i++)        {            if(str[i]=='('||str[i]=='['||str[i]=='{')               {ans[++top] = str[i];}            else if(str[i]=='}'||str[i]==']'||str[i]==')')             {                 if(top==0)                 {mat = 0;break;}                 else                 {                    if((str[i]==')'&&ans[top]=='(')||(str[i]==']'&&ans[top]=='[')||(str[i]=='}'&&ans[top]=='{'))                      {top--;}                   else {mat = 0;break;}                }             }        }         if(mat==1&&top!=0) mat = 0;      if(mat==1) cout<<"yes"<<endl;      else cout <<"no"<<endl;    }    return 0;}
阅读全文
0 0