-
Notifications
You must be signed in to change notification settings - Fork 0
/
괄호 변환.cpp
67 lines (60 loc) · 973 Bytes
/
괄호 변환.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
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
string p = "()";
int getBalance(string& s) {
int ret = 0;
int l=0, r=0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') l++;
else r++;
if (l == r) {
ret = i+1;
break;
}
}
return ret;
}
bool isRight(string& s) {
stack<int> st;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(') {
st.push(c);
}
else {
if (st.empty()) {
return false;
}
else {
st.pop();
}
}
}
return true;
}
string rev(string& s) {
string ret = "";
for (int i = 1;i<s.size()-1;i++) {
ret.push_back(s[i] == ')' ? '(' : ')');
}
return ret;
}
string solution(string p) {
if (p == "") return p;
string ret;
int sz = getBalance(p);
string w = p.substr(0, sz);
string u = p.substr(sz, p.size() - sz);
string k = solution(u);
if (isRight(w)) {
ret = w + k;
}
else {
ret = "("+k+")";
ret += rev(w);
}
return ret;
}