UVA673--Parentheses Balance

来源:互联网 发布:无间道3解析知乎 编辑:程序博客网 时间:2024/05/17 04:30

题意:
输入一个包含()和[]的括号序列,判断是否合法:
空串合法;
如果A、B都合法,则AB合法
如果A合法,则(A)和[A]合法

思路:
借助栈,左括号入栈,右括号如果匹配,栈顶出栈,继续,否则不合法。注意输入空行也合法。

代码:

#include<iostream>#include<string>#include<stdio.h>#include<stack>using namespace std;int main() {    int n;    cin >> n;    getchar();    while (n--) {        string str;        stack<char> st;        bool ok = true;        getline(cin, str);        if (str.empty()) {            cout << "Yes" << endl;            continue;        } else {            for (int i = 0; i < str.size(); i++) {                if (str[i] == '(' || str[i] == '[')                    st.push(str[i]);                else if (str[i] == ')') {                    if (st.empty())                        st.push(str[i]);                    if (st.top() == '(')                        st.pop();                } else if (str[i] == ']') {                    if (st.empty())                        st.push(str[i]);                    if (st.top() == '[')                        st.pop();                }            }        }        cout << (st.empty() ? "Yes" : "No") << endl;    }    return 0;}
0 0