题目:https://www.nowcoder.com/practice/3bad4a646b5b47b9b85e3dcb9488a8c3?tpId=40&tqId=30993&tPage=2&rp=2&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

栈的简单应用,但也写了二十多分钟

代码

  1. #include <cstdio>
  2. #include <stack>
  3. #include <string>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. string table = "(){}[]";
  8. stack<char> s;
  9. int main(){
  10. int n;
  11. while(scanf("%d", &n) != EOF){
  12. getchar();
  13. for(int i = 0; i < n; i++){
  14. string input;
  15. getline(cin, input);
  16. while(!s.empty()) s.pop(); // 清空栈
  17. s.push('#');
  18. for(int j = 0; j < input.size(); j++){
  19. if(table.find(input[j]) != string::npos){
  20. int pos = table.find(input[j]);
  21. if(pos % 2 == 0){
  22. s.push(input[j]);
  23. continue;
  24. }
  25. if(s.top() == table[pos - 1]){
  26. s.pop();
  27. } else s.push(input[j]);
  28. }
  29. }
  30. if(s.size() == 1) printf("yes\n");
  31. else printf("no\n");
  32. }
  33. }
  34. }