-
Notifications
You must be signed in to change notification settings - Fork 0
/
괄호변환.js
50 lines (39 loc) · 973 Bytes
/
괄호변환.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
44
45
46
47
48
49
50
// Solution 1
function checkBracket(p) {
const stack = [];
for (let i = 0; i < p.length; i++) {
if (p[i] === '(') {
stack.push('(');
} else {
if (stack.length === 0) {
return false;
}
stack.pop();
}
}
return stack.length === 0 ? true : false;
}
function solution(p) {
let result = '';
let openBracketCount = 0;
let closeBracketCount = 0;
if (p === '') {
return '';
}
for (let i = 0; i < p.length; i++) {
p[i] === '(' ? (openBracketCount += 1) : (closeBracketCount += 1);
if (openBracketCount === closeBracketCount) {
if (checkBracket(p.slice(0, i + 1))) {
result = p.slice(0, i + 1) + solution(p.slice(i + 1));
return result;
} else {
result = '(' + solution(p.slice(i + 1)) + ')';
for (let j = 1; j < i; j++) {
p[j] === '(' ? (result += ')') : (result += '(');
}
return result;
}
}
}
return answer;
}