728x90
스택 문제입니다.
괄호는 항상 '(' 와 ')'으로 이루어지며 한 쌍이 되어야 합니다.
) (와 같이 반대로 나와서는 안됩니다.
스택에 한글자씩 push해줍니다.
그리고 ')' 가 나왔을 때 스택의 top부분이
'('인지 확인합니다. 맞으면 '('를 pop()해줍니다.
이는 ')'가 나올때마다 한쌍씩 제거해주는 방식입니다.
그리고 모든 글자를 전부 탐색한 후 empty()를 확인해서
남아 있다면 쌍이 맞지 않는 경우이므로 틀렸다고 판단합니다.
#include <iostream>
#include <cstring>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
int n;
bool flag;
string str;
stack<char> s;
cin >> n;
for (int i = 0; i < n; ++i) {
flag = false;
while (!s.empty()) {
s.pop();
}
cin >> str;
for (int j = 0; j < str.size(); ++j) {
if (str[j] == ')') {
if (!s.empty() && s.top() == '(') {
s.pop();
}
else {
cout << "NO" << endl;
flag = true;
break;
}
}
else {
s.push(str[j]);
}
}
if (!s.empty()) {
cout << "NO" << endl;
flag = true;
}
if (flag == false) {
cout << "YES" << endl;
}
}
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 1874번 스택 수열 (0) | 2019.09.05 |
---|---|
[C++] 백준 4949번 균형잡힌 세상 (0) | 2019.09.04 |
[C++] 백준 2164번 카드2 (0) | 2019.09.04 |
[C++] 백준 10773번 제로 (0) | 2019.09.04 |
[C++] 백준 2004번 조합 0의 개수 (0) | 2019.09.04 |