hloj1182(括号匹配)

来源:互联网 发布:德国肥胖比例的数据网 编辑:程序博客网 时间:2024/06/05 23:01

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

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