一、题意

输入若干个括号序列,判断是否合法。注意可能输入空串,空串为合法。

二、解析

括号序列的判断,老栈题了。
注意由于有空串输入,所以需要用getline()。

三、代码

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int n;
string str;

int main() {
    cin >> n;
    cin.ignore();
    while(n --) {
        getline(cin, str);
        stack<char> stk;
        for(char ch : str) {
            if(stk.empty()) stk.push(ch);
            else {
                char top = stk.top();
                if(top == '(' && ch == ')' || top == '[' && ch == ']') stk.pop();
                else stk.push(ch);
            }
        }
        cout << (stk.empty() ? "Yes" : "No") << endl;
    }
}

四、归纳

  • 括号题目要想到栈
  • 用栈的题目时,一般可以单独考虑空栈情形
  • 若题目可能输入空串,要用getline(cin, str),因为cin>>string会忽视空行