이문제 단순해 보일 수 있는데 예제 입출력 부분에
'())(' 이런 경우 보고 예외 조건이 딱 생각이 났다.
단순히 '(' 나올 때 개수를 세는 식이 아니라
열고, 닫는다. 느낌으로 접근을 함.
문을 열지도 않았는데 닫는다는 건 말이 안되니까.
이런 "짝짓기"같은 문제 나오면은 항상
"stack"을 생각을 해야한다.
'('를 stack에다가 밀어 넣는데 마지막에
return stk.empty()가 있는 이유는 스택에 '('가 남아있으면 NO를 출력해야 하기 때문에.
stack<char > stk;
for (char c : s)
{
if (c == '(') stk.push(c);
else
{
if (!stk.empty()) stk.pop();
else return false;
}
}
return stk.empty();
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
#define endl "\n"
int n;
string s;
bool check(string s)
{
stack<char > stk;
for (char c : s)
{
if (c == '(') stk.push(c);
else
{
if (!stk.empty()) stk.pop();
else return false;
}
}
return stk.empty();
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> s;
if (check(s)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
#define endl "\n"
int n;
string s;
bool check(string s)
{
stack<char > stk;
for (char c : s)
{
if (c == '(') stk.push(c);
else
{
if (!stk.empty()) stk.pop();
else return false;
}
}
return stk.empty();
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> s;
if (check(s)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}