Algorithm/BOJ
[백준 알고리즘/C++/스택] 4949 균형잡힌 세상
pinevienna
2021. 4. 24. 18:42
세계의 균형을 체크하는 문제다..
영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어진 문자열에서 괄호 두 종류를 구분해야 한다
괄호를 닫을 때 stack.empty(), stack.top()을 체크해주면 된다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string str;
while (true) {
getline(cin, str);
if (str[0] == '.') break;
stack<char> stack;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(' || str[i] == '[')
stack.push(str[i]);
else if (str[i] == ')' || str[i] == ']') {
if (stack.empty()) {
cout << "no" << "\n";
break;
}
if (str[i] == ')' && stack.top() == '(')
stack.pop();
else if (str[i] == ']' && stack.top() == '[')
stack.pop();
else {
cout << "no" << "\n";
break;
}
}
if (str[i] == '.') {
if (stack.empty())
cout << "yes" << "\n";
else
cout << "no" << "\n";
}
}
}
}
|
cs |