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

来源:互联网 发布:mysql事务回滚 原理 编辑:程序博客网 时间:2024/05/01 02:28
数据结构实验之栈四:括号匹配

Time Limit: 1000MS    Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

sin(20+10)
{[}]

示例输出

yes
no
 
 
 
每当遇到( { 【 的时候  数据进栈
遇到)}】的时候出栈顶  看是否能匹配  如果能 则出栈   否则 结束
 
注意输入的时候有空格
#include<cstdio>#include<stack>#include<cstring>#include<iostream>#include<algorithm>#include<string.h>using namespace std;int main(){    stack<int>S;    string c;    while(getline(cin,c))    {        int flag=0;        while(!S.empty())        {            S.pop();        }        for(int i=0; i<c.size(); i++)        {            if(c[i]=='('||c[i]=='{'||c[i]=='[')            {                S.push(c[i]);            }            else if(c[i]==')')            {                if(S.empty())                {                    flag=1;                    break;                }                else                {                    char s;                    s=S.top();                    if(s=='(')                    {                        S.pop();                    }                    else                    {                        flag=1;                        break;                    }                }            }//            else if(c[i]==']')            {                if(S.empty())                {                    flag=1;                    break;                }                else                {                    char s;                    s=S.top();                    if(s=='[')                    {                        S.pop();                    }                    else                    {                        flag=1;                        break;                    }                }            }            //            else if(c[i]=='}')            {                if(S.empty())                {                    flag=1;                    break;                }                else                {                    char s;                    s=S.top();                    if(s=='{')                    {                        S.pop();                    }                    else                    {                        flag=1;                        break;                    }                }            }            if(flag==1)  break;        }        if(flag==0&&S.empty())  printf("yes\n");        else printf("no\n");    }    return 0;}/**************************************Problem id: SDUT OJ E User name: ACboy Result: Accepted Take Memory: 1568K Take Time: 0MS Submit Time: 2013-01-23 11:29:52  **************************************/