Stack and queue application 2: bracket matching

roblem Description

 Give you a string of characters, no more than 50 characters, which may include brackets, numbers, letters, punctuation marks, and spaces. Your task is to check whether the (), [], {} in this string of characters match.

 

Input

 There are multiple groups of input data, and the processing will reach the end of the file.

 

Output

 Output "yes" if it matches, output "no" if it doesn't match

 

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;
}

 

Guess you like

Origin blog.csdn.net/weixin_42137874/article/details/107716520