【C++】括号匹配

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
const int M=1024;

char a[M];

bool match()
{
    queue<char> q;
    int i=0;
    while(a[i]!='\0')
    {
        if(a[i]=='(')
        {
            q.push(a[i]);
        }
        if(a[i]==')')
        {
            if(q.empty())
                return false;
            else
                q.pop();
        }
        i++;
    }
    if(!q.empty())
        return false;
    else
        return true;
}

int main()
{
    memset(a,'\0',sizeof(a));
    while(scanf("%s",a))
    {
        if(match())
            cout<<1<<endl;
        else 
            cout<<0<<endl;
        memset(a,'\0',sizeof(a));
    }
    
    return 0;
}

 

经典的简单问题,网上的代码大都是自己实现辅助队列,算法描述并不直观,所以我用了一下STL类库,让代码简洁明了一点。

 

 

 

tz@HZAU

2019/3/15

posted on 2019-03-15 20:49  tuzhuo  阅读(255)  评论(0编辑  收藏  举报