uva673 Parentheses Balance

2016-11-16  本文已影响25人  科学旅行者

题目:

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
(a) if it is the empty string
(b) if A and B are correct, AB is correct,
(c) if A is correct, (A) and [A] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your
program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string
a line.
Output
A sequence of ‘Yes’ or ‘No’ on the output file.
Sample Input
3
([])
(([()])))
([()])()
Sample Output
Yes
No
Yes

就是简单的括号匹配,但须注意:
空串合法。
注意对回车字符的处理。
这道题可以使用栈这种数据结构解决。

参考代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
using namespace std;

class BalanceKuo {
    private:
        string s;//输入的字符串;
        vector<char> st;//栈;
    public:
        BalanceKuo() = default;//默认构造函数;
        BalanceKuo(string str) : s(str) {}//初始化构造器;
        void push(char c);
        bool isempty();
        void pop();
        void judge();   
};

void BalanceKuo::push(char c) {
    st.push_back(c);
}

bool BalanceKuo::isempty() {
    if (st.size() == 0) return true;
    else return false;
}

void BalanceKuo::pop() {
    st.pop_back();
}
//小心: ")))))))))))))]]]]]]]]]]]]"的情况;
void BalanceKuo::judge() {
    //cout << s[0] << endl;
    if (s[0] == ']' || s[0] == ')') {
        cout << "No" << endl;
        return;
    }
    for (int i = 0;i < s.length();++i) {
        if (s[i] == '(' || s[i] == '[') {
            push(s[i]);
        }
        else if (s[i] == ')') {
            if (!isempty()) {
                if (st[st.size()-1] == '(') pop();
                else {
                    cout << "No" << endl;
                    return;
                }
            }
            else {
                cout << "No" << endl;
                return;
            }
        }
        else if (s[i] == ']') {
            if (!isempty()) {
                if (st[st.size()-1] == '[') pop();
                else {
                    cout << "No" << endl;
                    return;
                } 
            }
            else {
                cout << "No" << endl;
                return;
            }
        }    
    }
    if (isempty()) cout << "Yes" << endl;//完全配对;
    else cout << "No" << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin >> n;
    string str;
    //getchar();
    cin.get();
    str.clear();
    while (n--) {
        //cin.get();
        getline(cin, str);
        BalanceKuo *b = new BalanceKuo(str);
        b -> judge();
        delete b;
    }
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读