function solution(p) {
var answer = '';
if(p.length===0){
return answer;
}else{
let left='';
let right='';
let open=0;
let close=0;
for(let i=0;i<p.length;i++){
if(p.charAt(i)==='('){
open++;
}else{
close++
}
if(open===close){
left=p.substring(0,open*2);
right=p.substring(open*2,p.length)
break;
}
}
if(isRight(left)){
answer=left+solution(right);
}else{
answer+='(';
answer+=solution(right)+')';
left=left.substring(1,left.length-1);
let LEFT='';
for(let i=0;i<left.length;i++){
if(left.charAt(i)==='('){
LEFT+=')'
}else LEFT+='(';
}
answer+=LEFT;
}
}
return answer;
}
function isRight(str){
let arr=[];
for(let i=0;i<str.length;i++){
let e=str.charAt(i);
if(e==='('){
arr.push(e)
}else{
if(arr.length===0||arr[arr.length-1]!=='(') return false
else arr.pop();
}
}
if(arr.length===0)return true;
else return false;
}