YTU OJ 2238: 括号匹配(栈和队列)

来源:互联网 发布:软件自学网cad2012 编辑:程序博客网 时间:2024/06/05 23:45

Description

假设一个算术表达式中可以包含三种括号:圆括号“(”和“)”,方括号“[”和“]”和花括号“{”和“ ”,且这三种括号可按任意的次序嵌套使用(如:…[{… …[]][]())。编写判别给定表达式中所含括号是否正确配对出现的算法。输出结果YES 或者 NO。

Input

5+{[2X5]+2}

Output

YES

Sample Input

8-[{2+7]}

Sample Output

NO

#include <stdio.h>#include<string.h>#include <stack>#include <iostream>using namespace std;int main(){    char s[100];    stack <char> x;    int i,b=1;    gets(s);    for(i=0; i<strlen(s); i++)    {        if(s[i]=='(')            x.push('(');        else if(s[i]=='[')            x.push('[');        else if(s[i]=='{')            x.push('{');        else if(s[i]==')')        {            if(x.top()!='(')                b=0;            else x.pop();        }        else if(s[i]==']')        {            if(x.top()!='[')                b=0;            else x.pop();        }        else if(s[i]=='}')        {            if(x.top()!='{')                b=0;            else x.pop();        }    }    if(!x.empty())b=0;    if(b==1)        printf("YES");    else printf("NO");    return 0;}