题意:
输入一个包含()和[]的括号序列,判断是否合法:
空串合法;
如果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;
}