Brackets Matching

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章