题解 括号匹配返回题目
官方题解
cpp 复制代码
#include "bits/stdc++.h"

signed main() {
	int t; std::cin >> t;
	while (t--){
		std::string s; std::cin >> s;
		std::stack<char> st;
		for (int i = 0; i < s.length(); ++i) {
			if (!st.empty()) {
				int top = st.top();
				if (top == '(' and s[i] == ')' or
					top == '[' and s[i] == ']' or
					top == '{' and s[i] == '}') 
				{
					st.pop();
				} else {
					st.push(s[i]);
				}
			} else {
				st.push(s[i]);
			}
		}
		if (st.empty()) std::cout << "YES\n";
		else std::cout << "NO\n";
	}

}
用户题解,共计1 份:
Avatar
ishark
#168 最后更新于:11/28/2024, 1:02:15 PM
复制代码
#include<iostream>
#include<stack>
#include<unordered_map>

using namespace std;

int main(){
   int T;
   cin >> T;
   getchar();

   unordered_map<char,char> mp = {{')','('},{']','['},{'}','{'}};

   while(T--){
       bool tag = true;
       string str;
       cin >> str;
       stack<char> st;

       for(char ch : str){
           if(ch == '(' || ch == '[' || ch == '{')st.push(ch);
           if(ch == ')' || ch == ']' || ch == '}'){
               if(st.empty() || st.top() != mp[ch]){
                   tag = false;
                   break;
               }
               st.pop();
           }
       }

       if(st.empty() && tag == true)cout << "YES" << endl;
       else cout << "NO" << endl;
   }
   return 0;
}
官方Q群
欢迎加入官方Q群反馈问题或寻求帮助。