fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<string> isValidBrackets(vector<string> queries) {
  5. vector<string> ans;
  6. ans.reserve(queries.size());
  7.  
  8. auto matches = [](char open, char close) {
  9. return (open == '(' && close == ')') ||
  10. (open == '[' && close == ']') ||
  11. (open == '{' && close == '}');
  12. };
  13.  
  14. for (const string &s : queries) {
  15. stack<char> st;
  16. bool ok = true;
  17. for (char c : s) {
  18. if (c == '(' || c == '[' || c == '{') {
  19. st.push(c);
  20. } else if (c == ')' || c == ']' || c == '}') {
  21. if (st.empty() || !matches(st.top(), c)) {
  22. ok = false;
  23. break;
  24. }
  25. st.pop();
  26. } else {
  27. // If other characters appear (not specified in prompt),
  28. // treat string invalid. (Adjust if needed)
  29. ok = false;
  30. break;
  31. }
  32. }
  33. if (!st.empty()) ok = false;
  34. ans.push_back(ok ? "YES" : "NO");
  35. }
  36. return ans;
  37. }
  38.  
  39. int main() {
  40. ios::sync_with_stdio(false);
  41. cin.tie(nullptr);
  42.  
  43. int q;
  44. if (!(cin >> q)) return 0;
  45. vector<string> queries;
  46. queries.reserve(q);
  47. string line;
  48. // consume possible endline after q
  49. getline(cin, line);
  50. for (int i = 0; i < q; ++i) {
  51. getline(cin, line);
  52. // If input may contain spaces trim them (but bracket strings usually don't have spaces)
  53. // remove leading/trailing spaces:
  54. size_t start = line.find_first_not_of(" \t\r\n");
  55. size_t end = line.find_last_not_of(" \t\r\n");
  56. if (start == string::npos) line = "";
  57. else line = line.substr(start, end - start + 1);
  58. queries.push_back(line);
  59. }
  60.  
  61. vector<string> res = isValidBrackets(queries);
  62. for (auto &r : res) cout << r << '\n';
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 5320KB
stdin
4
{([])
({[}])
[[]{()}]
(({})[)]
stdout
NO
NO
YES
NO