栈与队列应用二:括号匹配

roblem Description

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

Input

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

Output

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

Sample Input

sin(20+10)
{[}]

Sample Output

yes
no
#include<stdio.h>
#include<string.h>
#include <stack>
using namespace std;
stack<char>q;
int main()
{
    char st[66];
    int len, f;
    while(gets(st))
    {
        while(!q.empty())
            q.pop();
        len = strlen(st);
        f = 1;
        for(int i=0; i<len; i++)
        {
            if(st[i]=='('||st[i]=='{'||st[i]=='[')
                q.push(st[i]);
            else if(q.empty()&&(st[i]==')'||st[i]==']'||st[i]=='}'))
            {
                f=0;break;
            }
            else if(st[i]==')')
            {
                if(q.top()=='(')
                {
                    q.pop();
                }
                else
                {
                    f = 0;
                    break;
                }
            }
            else if(st[i]==']')
            {
                if(q.top()=='[') q.pop();
                else
                {
                    f = 0;break;
                }
            }
            else if(st[i]=='}')
            {
                if(q.top()=='{') q.pop();
                else{
                    f=0;break;
                }
            }
        }
        if(!q.empty()) f = 0;
        if(f==1)
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/107716520
今日推荐