#include <bits/stdc++.h>
using namespace std;
vector<string> isValidBrackets(vector<string> queries) {
vector<string> ans;
ans.reserve(queries.size());
auto matches = [](char open, char close) {
return (open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}');
};
for (const string &s : queries) {
stack<char> st;
bool ok = true;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (st.empty() || !matches(st.top(), c)) {
ok = false;
break;
}
st.pop();
} else {
// If other characters appear (not specified in prompt),
// treat string invalid. (Adjust if needed)
ok = false;
break;
}
}
if (!st.empty()) ok = false;
ans.push_back(ok ? "YES" : "NO");
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
if (!(cin >> q)) return 0;
vector<string> queries;
queries.reserve(q);
string line;
// consume possible endline after q
getline(cin, line);
for (int i = 0; i < q; ++i) {
getline(cin, line);
// If input may contain spaces trim them (but bracket strings usually don't have spaces)
// remove leading/trailing spaces:
size_t start = line.find_first_not_of(" \t\r\n");
size_t end = line.find_last_not_of(" \t\r\n");
if (start == string::npos) line = "";
else line = line.substr(start, end - start + 1);
queries.push_back(line);
}
vector<string> res = isValidBrackets(queries);
for (auto &r : res) cout << r << '\n';
return 0;
}