-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lv.2.괄호 변환.js
43 lines (38 loc) · 862 Bytes
/
Lv.2.괄호 변환.js
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
function solution(p) {
var answer = "";
var open = 0;
var close = 0;
if (!p) return "";
for (let i = 0; i < p.length; i++) {
if (p[i] === "(") open++;
else close++;
if (open === close) {
if (check(p.slice(0, i + 1))) {
answer = p.slice(0, i + 1) + solution(p.slice(i + 1));
return answer;
} else {
answer = "(" + solution(p.slice(i + 1)) + ")";
for (let j = 1; j < i; j++) {
if (p[j] === "(") {
answer = answer + ")";
} else {
answer = answer + "(";
}
}
// 4-5
return answer;
}
}
}
}
function check(p) {
var stack = [];
for (let i = 0; i < p.length; i++) {
if (p[i] === "(") stack.push("(");
else {
if (stack.length === 0) return false;
stack.pop();
}
}
return true;
}