<Sicily>Brackets Matching

来源:互联网 发布:佳能数码单反相机软件 编辑:程序博客网 时间:2024/05/19 11:36

一、题目描述

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;}
0 0
原创粉丝点击