<Sicily>Brackets Matching

一、题目描述

Let us define a regular brackets sequence in the following way:

  1. Empty sequence is a regular sequence.

  2. If S is a regular sequence, then (S) , [S] and {S} are both regular sequences.

  3. If A and B are regular sequences, then AB is a regular sequence.

For example, all of the following sequences of characters are regular brackets sequences:

(), [], {}, (){[]}

While the following character sequences are not:

(, [, {, )(, ([)], {[(]

Write a program to judge whether a given sequence is a regular bracket sequence or not.

二、输入

The input may contain several test cases.

The first line of each test case contains the length of the bracket sequence N (1<=N<=100). The second line contains N characters including ‘(‘, ‘)’, ‘[‘, ‘]’,’{‘ or ’}’.

Input is terminated by EOF.

三、输出

For each test case, if the sequence is a regular brackets sequence, output “YES” on a single line, else output “NO”.

例如:
输入:
2
()
4
((]]
6
{[]}()
输出:
YES
NO
YES

四、解题思路

这个使用栈来处理,当栈顶不为空的时候,栈顶跟输入的字符(括号)匹配,是否为一对(栈顶的为左边括号,新输入的为右边括号)。若能匹配,pop出栈顶,继续新的输入,否则新输入的字符入栈。

五、代码

#include<iostream>
#include<stack>
#include <stdio.h>

using namespace std;

int main()
{
    int leng;

    while(cin >> leng)
    {
        stack<char> strStack;
        for(int i = 0; i < leng; i++)
        {
            char nowChar;
            cin >> nowChar;
            if(strStack.empty()){strStack.push(nowChar); continue;} //如果栈为空,直接入栈,不需要判断
            if(nowChar == '(' || nowChar  == '[' || nowChar == '{'){strStack.push(nowChar); continue;}  //如果是左边的括号,直接入栈
            if(nowChar == ')' && strStack.top() == '('){strStack.pop();}    //“()”匹配成功
            else if(nowChar == ']' && strStack.top() == '['){strStack.pop();}       //“[]”匹配成功
            else if(nowChar == '}' && strStack.top() == '{') {strStack.pop();}      //“{}”匹配成功
            else {strStack.push(nowChar);}  //匹配不成功,入栈
        }

        if(strStack.empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }

    return 0;
}
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值