hloj1182(括号匹配)

     这道题就是考考栈结构的应用。

      先开一个数组作为栈,接着从左到右扫描括号序列,每次扫到一个括号,就将其于栈顶括号进行比较(当栈为空时,直接入栈),若栈顶括号为‘(’,且扫到的括号为‘)’,则弹出栈顶括号,并继续扫描括号序列的下一个括号,否则就将扫到的括号压入栈中。一直重复这个过程,直到扫完括号序列。此时,若栈为空,则说明所给括号序列是都匹配的,否则输出"NO".

     代码如下:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
const int M=1010;
const int N=100010;
int n;
char c[N];
int main()
{
    //freopen("E:\\in.txt","r",stdin);
    //freopen("E:\\out.txt","w",stdout);
    while(~scanf("%s",c))
    {
        n=strlen(c);
        char s[N];
        int top=0,num=0;
        for (int i=0;i<n;i++){
            if (!top) s[top++]=c[i];   // 若栈为空,直接入栈
            else {
                if (c[i]==')' && s[top-1]=='(')  { top--; num++; }  // 若栈顶括号跟扫描到的括号匹配,就将其弹出,计数器+1
                else s[top++]=c[i];  //  不匹配就直接入栈
            }
        }
        if (!top)  // 判断栈是否为空
           printf("%d\n",num);
        else puts("NO");
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值