#include <bits/stdc++.h>
using namespace std;
#define maxn 500
char ca[maxn];
stack<char>a;//<>
stack<char>b;//()
stack<char>c;//[]
stack<char>d;//{}
stack<char>s;
//<>,(),[],{}
inline bool check(char*cc){
int i=0;
while(i<=strlen(cc)-1){
if(cc[i]=='<'){
a.push(cc[i]); s.push(cc[i]);
}
if(cc[i]=='>'){
if(!s.empty() and !a.empty() and s.top()=='<'){
a.pop(); s.pop();
}
else return 0;
}
if(cc[i]=='('){
if(!a.empty()){
if(a.top()!='<'){
b.push(cc[i]); s.push(cc[i]);
}
else return 0;
}
if(a.empty()){
b.push(cc[i]); s.push(cc[i]);
}
}
if(cc[i]==')'){
if(!s.empty() and !b.empty() and s.top()=='('){
b.pop(); s.pop();
}
else return 0;
}
if(cc[i]=='['){
if(!a.empty() and !b.empty()){
if(a.top()!='<' and b.top()!='('){
c.push(cc[i]); s.push(cc[i]);
}
else return 0;
}
if(a.empty() and b.empty()){
c.push(cc[i]); s.push(cc[i]);
}
}
if(cc[i]==']'){
if(!s.empty() and !c.empty()){
c.pop(); s.pop();
}
else return 0;
}
if(cc[i]=='{'){
if(!a.empty() and !b.empty() and !c.empty()){
if(a.top()!='<' and b.top()!='(' and c.top()!='['){
d.push(cc[i]); s.push(cc[i]);
}
else return 0;
}
if(a.empty() and b.empty() and c.empty()){
d.push(cc[i]); s.push(cc[i]);
}
}
if(cc[i]=='}'){
if(!s.empty() and !d.empty()){
d.pop(); s.pop();
}
else return 0;
}
i++;
}
if(!s.empty()) return 0;
else return 1;
}
inline int clear(){
int n1=s.size(),n2=a.size(),n3=b.size(),n4=c.size(),n5=d.size();
for(int i=0;i<n1;i++) s.pop();
for(int i=0;i<n2;i++) a.pop();
for(int i=0;i<n3;i++) b.pop();
for(int i=0;i<n4;i++) c.pop();
for(int i=0;i<n5;i++) d.pop();
}
int main(){
ios::sync_with_stdio(false);
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>ca;
clear();
//cout<<s.size()<<endl;
int ans=check(ca);
if(ans==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
一本通上的题