#include <iostream>
#include <string>
#include <stack>
using namespace std;

int getPriority(char c) {
    switch (c) {
        case '{':
        case '}':
            return 4;
        case '[':
        case ']':
            return 3;
        case '(':
        case ')':
            return 2;
        case '<':
        case '>':
            return 1;
        default:
            return 0;
    }
}
bool isPair(char a, char b) {
    return (a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' &&
            b == ')') || (a == '<' && b == '>');
}
int main() {
    int T;
    cin >> T;
    while (T--) {
        string s;
        cin >> s;
        stack<char> st;
        bool isValid = true;
        for (char c : s) {
            if (c == '(' || c == '{' || c == '[' || c == '<') {
                if (!st.empty()) {
                    char top = st.top();
                    if (getPriority(c) > getPriority(top)) {
                        isValid = false;
                        break;
                    }
                }
                st.push(c);
            } else {
                if (st.empty()) {
                    isValid = false;
                    break;
                }
                char top = st.top();
                if (isPair(top, c)) {
                    st.pop();
                } else {
                    isValid = false;
                    break;
                }
            }
        }
        if (st.empty() && isValid) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }
    return 0;
}
// 64 位输出请用 printf("%lld")