#include <bits/stdc++.h>

using namespace std;

// Complete the isBalanced function below.
string isBalanced(string s) {
    string ans="";
    stack<char>st;
    int op1=0,op2=0,op3=0;
    int cl1=0,cl2=0,cl3=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='[')
        op2++;
        else if(s[i]=='{')
        op3++;
        else if(s[i]=='(')
        op1++;
        else if(s[i]=='}')
        cl3++;
        else if(s[i]==']')
        cl2++;
        else {
        cl1++;
        }
     }
     if(cl1!=op1||cl2!=op2||cl3!=op3)
     return "NO";
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='{'||s[i]=='['||s[i]=='(')
        {
            st.push(s[i]);
        }
        else {
            if(st.size())
            {
                if(s[i]==')')
                {
                    if(st.top()!='(')
                        return "NO";
                    else {
                        st.pop();
                    }
                }
                else if(s[i]==']')
                {

                    if(st.top()!='[')
                        return "NO";
                     else {
                        st.pop();
                    }
                }
                else if(s[i]=='}')
                {

                    if(st.top()!='{')
                        return "NO";
                 else {
                        st.pop();
                    }
                }
            }
            else {
                return "NO";
            }
        }
    }
    
    return "YES";
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int t;
    cin >> t;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    for (int t_itr = 0; t_itr < t; t_itr++) {
        string s;
        getline(cin, s);

        string result = isBalanced(s);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}