STL栈 D - Parentheses Balance S

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

(a) if it is the empty string

(b) if A and B are correct, AB is correct,

(c) if A is correct, (A) and [A] is correct.

Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.

Input

The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string a line.

Output

A sequence of ‘Yes’ or ‘No’ on the output file. 


给你一个由圆括号( )和[组成的字符串。这种类型的字符串被认为是正确的: ( A )如果是空字符串,( B )如果A和B是正确的,AB是正确的,( c )如果A是正确的,( A )和[ A ]是正确的。编写一个程序,接受这种类型的字符串序列,并检查它们的正确性。您的程序可以假设最大字符串长度为128。输入文件包含一个正整数n和一系列n个圆括号' ( ) '和' [ ',一行一个字符串。在输出文件上输出一系列“是”或“否”。


题意即为:输入括号()或[ ],   判断输入的括号们 是否 规范 成对 相对应。


Sample Input

3

([])

(([()])))

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

Sample Output

Yes

No

Yes


#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
    int n;
    scanf("%d",&n);  //三个例子;
    getchar(); 
    while(n--)
    {
        int flag=1;
        char k;
        stack<char>s;  //定义字符型栈s;
        while((k=getchar())!='\n')  //当k不为回车,即还未到最后一个;
        {
           //如果k为括号 ( 或 [ ,元素k入栈;
            if(k=='('||k=='[')
                s.push(k);
           //如果k为括号 ) 或 ] ;
            if(k==')'||k==']')
            {
               //如果栈中已空,即没有与之对应的,则记flag为零
                if(s.empty())
                    flag=0;
               //如果栈中不为空,并且栈的顶部与此括号对应,则弹出栈顶元素;
                else if((s.top()=='('&&k==')')||(s.top()=='['&&k==']'))
                    s.pop();
            }
        }
        //当flag为1,说明没有出现过不对应情况,并且栈中已全部对应完,则输出YES;
        if(flag==1&&s.empty())
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值