括号匹配(栈)

括号配对问题

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

难度:3

输入

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符

输出

每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No

样例输入

3
[(])
(])
([[]()])

样例输出

No
No
Yes

描述

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

通过这一道题可以更直观的了解到栈的运用

栈的头文件为#include<stack>

如果定义栈为s

入栈:s.push() 出栈:s.pop()

访问栈顶元素:s.top() 计算栈内元素s.size()

s.empty()判断栈内是否为空

#include <iostream>
#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;
int main()
{
    stack<char> s;
    int a,i;
    char b[10000];
    scanf("%d",&a);
    while(a--)
    {
        while(!s.empty())
            s.pop();
        scanf("%s",&b);
        for(i=0;i<strlen(b);i++)
        {
            if(b[i]=='('||b[i]=='[')
                s.push(b[i]);
            else if(!s.empty())
            {
                if(b[i]==')'&&s.top()=='('||b[i]==']'&&s.top()=='[')
                {s.pop();}
                else break;
            }
            else break;
        }
        if(i==strlen(b))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/acm147258369/article/details/83896227