forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4.cpp
54 lines (50 loc) Β· 1.52 KB
/
4.cpp
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;
}