NYOJ002 括号配对问题(栈)

115 阅读1分钟

题目:

括号配对问题

时间限制: 3000 ms  |  内存限制: 65535 KB

难度: 3

    • 描述

    • 现在,有一行括号序列,请你检查这行括号是否配对。

        • 输入
        • 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
        • 输出
        • 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
        • 样例输入
        • 3
          [(])
          (])
          ([[]()])
          
        • 样例输出
        • No
          No
          Yes
          

代码:

#include<stdio.h>
#include<string.h>
int peidui(char a,char b)//检测是否括号配对
{
    if (a==')'&&b=='(')
        return 1;
    if (a==']'&&b=='[')
        return 1;
    return 0;
}
int main()
{
    int t;
    scanf("%d",&t);
    getchar();
    while (t--)
    {
        char s[10001]= {0},ch[10001]= {0};
        int top=0,len,num=0;
        gets(s);//写入字符串到数组
        len=strlen(s);
        if (len%2==1)
        {
            printf("No\n");//奇数不可能配对
        }
        else
        {
            for (int i=0; i<len; i++)
            {

                if (s[i]=='('||s[i]=='[')
                    ch[top++]=s[i];//当当前的值是左括号时,压栈进入top
                //printf("ch[%d]=%c,s[%d]=%c\n",top-1,ch[top-1],i,s[i]);
                if (s[i]==')'||s[i]==']')//检测当前的值是否和栈中的括号配对
                {
                    if (peidui(s[i],ch[top-1]))
                    {
                       // printf("第二s[%d]=%c,ch[%d]=%c\n",i,s[i],top-1,ch[top-1]);
                        top--;//如果两个括号符配对,出栈
                        num++;//表示已经配对一组括号
                    }
                }
            }
            if (num==len/2)//检测配对的括号是否是总长度的一半
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}

代码2(利用栈):

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stack>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
char ss[100005];
stack<char>s;
int peidui(char a,char b)
{
    if(a=='['&&b==']')
        return 1;
    if(a=='('&&b==')')
        return 1;
    return 0;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        while(!s.empty())
            s.pop();
        int num=0;
        mem(ss,'\0');
        scanf("%s",ss);
        int len=strlen(ss);
        if(len%2==1)
        {
            printf("No\n");
        }
        else
        {
            for(int i=0; i<len; i++)
            {
                if(ss[i]=='['||ss[i]=='(')
                    s.push(ss[i]);
                if(ss[i]==']'||ss[i]==')')
                {

                    if(!s.empty())//这里一定要判断栈是否为空
                        if(peidui(s.top(),ss[i]))
                        {
                            num++;
                            s.pop();
                        }
                }

            }
            if (num==len/2)
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}


\

\

ps:初学栈,存代码

\