括号配对
题目传送门:点击打开链接
早上爬起来就只写了这一个题,苦逼。两种方法。
//使用stl求解 #include <iostream> #include <cstring> #include <string> #include <algorithm> using namespace std; string s ; int pos = 0; void del(string s, int & pos) { int flag = 1; for (int i =0; i<s.size() && flag; i++) { if ((s[i] == '(' && s[i+1] == ')') || (s[i] == '[' && s[i+1] == ']')) { pos = i; flag = 0; } } if (flag == 1) pos = -5; } int main() { int n; cin >> n; while (n --) { cin >> s; del(s, pos); while (pos>=0 && s.size()>0) { s.erase(pos, 2); del(s, pos); } if (pos < 0 && s.size() == 0) cout << "Yes"<< endl; else cout << "No"<< endl; } return 0; }
//使用栈 #include <iostream> #include <string> #include <stack> using namespace std; int main() { int n; cin >> n; while (n --) { int flag = 0; string s ; cin >> s; stack <char> p; for (int i = 0; i<s.size() && flag == 0; i++) { if (s[i] == '(' || s[i] == '[') p.push(s[i]); else { if (p.empty()) flag = 1; else if ((s[i] == ')' && p.top() == '(') || (s[i] == ']' && p.top() == '[')) p.pop(); else p.push(s[i]); } } if (!p.empty() || flag == 1) cout << "No"<< endl; else cout << "Yes"<< endl; } return 0 ; }