<Sicily>Brackets Matching
来源:互联网 发布:佳能数码单反相机软件 编辑:程序博客网 时间:2024/05/19 11:36
一、题目描述
Let us define a regular brackets sequence in the following way:
Empty sequence is a regular sequence.
If S is a regular sequence, then (S) , [S] and {S} are both regular sequences.
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;}
- <Sicily>Brackets Matching
- <OJ_Sicily>Brackets Matching
- Sicily 1543 Completing Brackets
- Sicily 1543. Completing Brackets
- Sicily 6137. Removing Brackets
- Sicily 1543. Completing Brackets
- sicily 1035 DNA matching
- sicily--1035. DNA matching
- Sicily 1035. DNA matching
- sicily 1035. DNA matching
- sicily 1035. DNA matching
- sicily 1035.DNA Matching
- sicily DNA matching
- Sicily 1035. DNA matching
- Sicily 1035 DNA matching
- Sicily 1035 DNA matching
- sicily 1035. DNA matching
- [sicily]1035. DNA matching
- [转]Statement和PreparedStatement批量更新
- 谷歌page-rank搜索算法 相关知识
- 模板匹配
- LOCAL_LDLIBS报错
- 浏览器端JS导出EXCEL
- <Sicily>Brackets Matching
- WebStorm下载,破解,汉化,debug调试,以及会debug会出现的问题
- Linux中安装PHP的pdo_mysql扩展的详细解决方案
- 1基于getopts和case组合使用
- uitableview cell上加载webview
- react-redux 学习笔记
- 根据文字计算label的高度
- ASmack4.0.7详细讲解
- 解决错误java compiler level does not match the version of the installed java project facet