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

来源:互联网 发布:h5牛牛源码下载 编辑:程序博客网 时间:2024/05/16 14:45

题目链接:点击打开链接

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

sin(20+10){[}]

示例输出

yesno

提示

 

代码实现:

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>using namespace std;int main(){    char a[55],b[55];    int flag;    int top;    int n;    while(gets(a)!=NULL)    {        memset(b,0,sizeof(b));        flag=1;        top=0;        n=strlen(a);        for(int i=0;i<n;i++)        {            if(a[i]=='('||a[i]=='['||a[i]=='{')///左半边进栈                b[top++]=a[i];            else if(a[i]==')')///右半边            {                if(top==0)///栈为空                {                    flag=0;                    break;///跳出循环                }                else                {                    char st=b[top-1];                    if(st=='(')///互相匹配则出栈                    {                        top--;                    }                    else                    {                        flag=0;                        break;                    }                }            }            else if(a[i]==']')            {                if(top==0)                {                    flag=0;                    break;                }                else                {                    char st=b[top-1];                    if(st=='[')                    {                        top--;                    }                    else                    {                        flag=0;                        break;                    }                }            }            else if(a[i]=='}')            {                if(top==0)                {                    flag=0;                    break;                }                else                {                    char st=b[top-1];                    if(st=='{')                    {                        top--;                    }                    else                    {                        flag=0;                        break;                    }                }            }        }///for        if(flag==1&&top==0)            printf("yes\n");        else            printf("no\n");    }///while    return 0;}


 

0 1
原创粉丝点击