๐ฅ๋ฌธ์ ๋งํฌ
https://school.programmers.co.kr/learn/courses/30/lessons/60058
๐ฅํ์ด
์ด ๋ฌธ์ ๋ ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ์ฌ ์ฃผ์ด์ง ๋ณํ์ ์ง์์ ์ผ๋ก ํ ์ ์๋์ง๋ฅผ ํ์ธํ๋ ๋ฌธ์ ์ด๋ค.
์ฌ๊ท ํจ์๋ฅผ ์งํํ๊ธฐ ์ํด ํ์ํ ํจ์ ๋๊ฐ๋ฅผ( ๊ท ํ์กํ ๊ดํธ ๋ฌธ์์ด์ธ์ง ํ๋จ ํ๋ ํจ์ => is_balanced_string, ์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด์ธ์ง ํ๋จํ๋ ํจ์ =>is_right_string ) ์ ์ํ๊ณ ์ด๋ฅผ ์ฌ๊ทํจ์ ๋ด๋ถ์์ ์ด์ฉํ์ฌ ๋ถ๊ธฐ์ฒ๋ฆฌ ํ๋ค.
function solution(p) {
const is_balanced_string=(str)=>{
let [open_flag,close_flag]=[0,0]
let str_arr = str.split('')
str_arr.forEach((cha)=>{
if(cha==='('){
open_flag+=1
}else{
close_flag+=1
}
})
return open_flag===close_flag
}
const is_right_string=(str)=>{
let arr =[]
let str_arr = [...str]
for(const cha of str_arr){
if(cha==='('){
arr.push('(')
}else if(cha===')'){
if(arr.at(-1) && arr.at(-1) === '('){
arr.pop()
}else{
arr.push(')')
break;
}
}
}
return arr.length===0
}
// ๋น ๋ฌธ์์ด์ธ ๊ฒฝ์ฐ
if(p.length===0) return p
// ์ฌ๋ฐ๋ฅธ ๋ฌธ์์ด์ธ ๊ฒฝ์ฐ
if(is_right_string(p)) return p
let answer =''
const recursive=(str)=>{
if(!str || str===''){
return
}
if(is_right_string(str)){
answer+=str
return
}
let str_arr= str.split('')
let u=''
let v=''
while(1){
let cha = str_arr.shift()
if(!cha){ break;}
u+=cha
if(is_balanced_string(u)){
if(is_right_string(u)){
answer+=u
let v=str_arr.join('') // '' ์ผ ์ ์์
recursive(v)
break;
}else{
let new_arr = [...u]
let v=str_arr.join('')
answer+='('
recursive(v)
answer+=')'
new_arr.shift()
new_arr.pop()
new_arr=new_arr.map((cha)=>{
return cha==='(' ? ')': '('
})
let reversed_string=new_arr.join('')
answer+=reversed_string
break;
}
}
}
}
recursive(p)
return answer;
}
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ๊ฑฐ์ค๋ฆ๋ (2) | 2024.09.06 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ๋ฆฌ์ฝ์ณ ๋ก๋ด (0) | 2024.08.25 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ์ด๋ชจํฐ์ฝ ํ ์ธํ์ฌ (0) | 2024.08.24 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ๋จ์ด๋ณํ (0) | 2024.08.24 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ์์ (0) | 2024.08.15 |