思路:用stack从左到右处理字符串,同种括号出栈异种入栈
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <map>
#include <set>
#include <stack>
using namespace std;
char f(char c) {
if (c == ')')
return '(';
if (c == ']')
return '[';
return 0;
}
bool judge(const string& s) {
stack<char> st;
st.push('0');
for (int i = 0; i < s.size(); i++) {
if (st.top() != f(s[i])) //与栈顶括号同种栈顶出栈,异种后者入栈
st.push(s[i]);
else
st.pop();
}
return st.size() == 1; //栈中只剩下'0'
}
int main(void) {
int n;
string s;
while (cin >> n) {
getchar();
while (n--) {
getline(cin, s);
if (s.size() == 0 || judge(s))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}
return 0;
}