您的位置:首页 > 其它

<OJ_Sicily>Brackets Matching

2016-06-13 19:47 232 查看
Description
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.
Input
 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.
Output
For each test case, if the sequence is a regular brackets sequence, output “YES” on a single line, else output “NO”. 
题目解释:这道题是为了实现括号匹配。
解题思路:使用栈,在存储符号的过程中,若发现成对出现的便消除,到最后栈为空说明输入的符号都是成对存在且匹配的,若到最后栈不为空,说明不成对匹配
#include <iostream>
#include <stack>
using namespace std;
bool match(char *a, char *b){ // 判断两个字符是否匹配
if (*a == '(' && *b == ')') return true;
if (*a == '[' && *b == ']') return true;
if (*a == '{' && *b == '}') return true;
return false;
}
int main(int argc, const char * argv[]) {
// insert code here...
int len;
while (cin >> len) {
stack<char> st;
char tmp ;
for (int i = 0; i < len; i++) { // 逐个字符输入栈并且与栈顶的元素进行比较匹配
cin >> tmp;
if (!st.empty()) {
char topch = st.top();
if (match(&topch, &tmp)) {
st.pop();
continue;
}
}
st.push(tmp);
}
if (!st.empty()) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sicily 算法