문제출처
const checkRight = (u) => {
let stack = [];
for (let i=0; i<u.length; i++) {
if (u[i] === '(') stack.push('(');
else {
if (stack.length === 0) return false;
stack.pop();
}
}
return true;
};
const divide = (str) => {
let stack = [str[0]];
for (let i=1; i<str.length; i++) {
if (stack[0] === str[i]) stack.push(str[i]);
else {
stack.pop();
}
if (stack.length === 0) {
const s = str.join('');
return [s.substring(0, i+1), s.substring(i+1)];
}
}
return [str.join(''), ''];
};
const change = (u) => {
let str = '';
for (let i=1; i<u.length-1; i++) {
if (u[i] === '(') str += ')';
else str += '(';
}
return str;
};
function solution(p) {
let answer = '';
let str = p.split('');
while (answer.length < p.length) {
const [u, v] = divide(str);
const rightU = checkRight(u);
if (rightU) answer += u;
else answer += '(' + solution(v) + ')' + change(u);
str = str.slice(u.length);
}
return answer;
}