括号匹配(栈和队列)

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

Input
5+{[2X5]+2}

Output
YES

Sample Input
8-[{2+7]}
Sample Output
NO

///这个程序存在问题,按照题意三种括号成对存在,成对出现,后台可能也是这样安排的,但对比第一个例题,若是右括号多余左括号那么就不行了
#include<iostream>
#include<stack>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    int len,i,j;
    char x[601];
    gets(x);
    len=strlen(x);
    stack<char>s;
    s.push('#');
    for(i=0; i<len; i++)
    {
        if((x[i]=='(')||(x[i]=='[')||(x[i]=='{'))
            s.push(x[i]);///压入栈
        else if((x[i]==')'&&s.top()=='(')||(x[i]==']'&&s.top()=='[')||(x[i]=='}'&&s.top()=='{'))
        {
                s.pop();///出栈
        }
    }
    if(s.top()=='#')
        printf("YES\n");
    else
        printf("NO\n");
return 0;
}

 

posted @ 2018-03-28 23:08  王陸  阅读(973)  评论(0编辑  收藏  举报