괄호 '('와 ')'의 개수가 동일해야 하고, 무조건 '('가 먼저 와야하는 것을 봤을 때 스택을 이용해 해결할 수 있습니다.
'('가 오면 스택을 쌓고 ')'가 오면 빼면 됩니다.
#include<iostream>
int main()
{
int t;
std::cin >> t;
std::string str;
int stack[51];
for (int i = 0; i < t; i++)
{
std::cin >> str;
bool result = true;
int len = str.size();
std::fill_n(stack, 51, -1);
int cur_top = -1;
for (int j = 0; j < len; j++)
{
if (str[j] == '(')
str[++cur_top] = 1;
else
{
if (cur_top == -1)
{
result = false;
break;
}
str[cur_top--] = -1;
}
}
if (cur_top == -1 && result)
std::cout << "YES\n";
else
std::cout << "NO\n";
}
return 0;
}