#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string st;
stack<char> stk;
int index = 0;
cin >> st;
if (st[0] == ')') { //첫번째 괄호가 ) 일때 무조건 NO
cout << "NO" << "\n";
continue;
}
else {
while (index < st.length()) {
if (stk.empty() && st[index] != ')') {
stk.push(st[index++]);
}
else if (stk.empty()) {
stk.push(st[index++]);
}
else if (stk.top() == st[index]) {
stk.push(st[index++]);
}
else if (stk.top() != st[index] && stk.top() != ')') {
stk.pop();
index++;
}
}
}
if (stk.empty()) { cout << "YES\n"; }
else { cout << "NO\n"; }
}
}
시간초과
불필요한 while문 사용으로 인한 시간초과
두번째 코드
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string st;
stack<char> stk;
int index = 0;
cin >> st;
for (int index = 0; index < st.length(); index++) {
if (stk.empty() || stk.top() == st[index]) {
stk.push(st[index]);
}
else if (stk.top() != ')') {
stk.pop();
}
}
if (stk.empty()) { cout << "YES\n"; }
else { cout << "NO\n"; }
}
}