forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.cpp
More file actions
54 lines (50 loc) ยท 1.52 KB
/
4.cpp
File metadata and controls
54 lines (50 loc) ยท 1.52 KB
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
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
// "๊ท ํ์กํ ๊ดํธ ๋ฌธ์์ด"์ ์ธ๋ฑ์ค ๋ฐํ
int balancedIndex(string p) {
int count = 0; // ์ผ์ชฝ ๊ดํธ์ ๊ฐ์
for (int i = 0; i < p.size(); i++) {
if (p[i] == '(') count += 1;
else count -= 1;
if (count == 0) return i;
}
return -1;
}
// "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ธ์ง ํ๋จ
bool checkProper(string p) {
int count = 0; // ์ผ์ชฝ ๊ดํธ์ ๊ฐ์
for (int i = 0; i < p.size(); i++) {
if (p[i] == '(') count += 1;
else {
if (count == 0) { // ์์ด ๋ง์ง ์๋ ๊ฒฝ์ฐ์ false ๋ฐํ
return false;
}
count -= 1;
}
}
return true; // ์์ด ๋ง๋ ๊ฒฝ์ฐ์ true ๋ฐํ
}
string solution(string p) {
string answer = "";
if (p == "") return answer;
int index = balancedIndex(p);
string u = p.substr(0, index + 1);
string v = p.substr(index + 1);
// "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ด๋ฉด, v์ ๋ํด ํจ์๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ๋ถ์ฌ ๋ฐํ
if (checkProper(u)) {
answer = u + solution(v);
}
// "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ด ์๋๋ผ๋ฉด ์๋์ ๊ณผ์ ์ ์ํ
else {
answer = "(";
answer += solution(v);
answer += ")";
u = u.substr(1, u.size() - 2); // ์ฒซ ๋ฒ์งธ์ ๋ง์ง๋ง ๋ฌธ์๋ฅผ ์ ๊ฑฐ
for (int i = 0; i < u.size(); i++) {
if (u[i] == '(') u[i] = ')';
else u[i] = '(';
}
answer += u;
}
return answer;
}