๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] 24 - ํšŒ๋ฌธ ๋ฌธ์ž์—ด

by YWTechIT 2021. 8. 17.
728x90

๐Ÿ“ 24 - ํšŒ๋ฌธ ๋ฌธ์ž์—ด

์ด๋ฒˆ ์„น์…˜์€ ๋ฌธ์ž์—ด ํƒ์ƒ‰์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ์„น์…˜์ด๋‹ค.

 

์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด ํšŒ๋ฌธ์ธ์ง€ ํŒ๋ณ„ํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ์ด์ „์— ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ธํ„ฐ๋ทฐ์—์„œ ํ•œ๋ฒˆ ํ’€์–ด๋ณธ์ ์ด ์žˆ๋‹ค. ๋งˆ์ง€๋ง‰์— ์žฌ๊ท€๋กœ๋„ ํ•œ๋ฒˆ ํ’€์–ด๋ดค๋‹ค.

 

console.log(solution("gooog"));

// split + reverse + join
function solution(str){
    if (str.split('').reverse().join('') !== str) return false;
    return true
}

 

console.log(solution("gooog"));

// for
function solution(str){
    str = str.toLowerCase();
    let n = str.length

    for (let i=0; i<Math.floor(n/2); i++){
        if (str[i] !== str[n-i-1]) return false
    }
    return true
}

 

console.log(solution("gooog"));

// slice
function solution(str){
    str = str.toLowerCase();

    while (str.length > 1){
        if (str.slice(0, 1) === str.slice(-1)) str = str.slice(1, -1);
        else return false;
        console.log(str)
    }
    return true;
}

 

console.log(solution("gooog"));

// recursive
function firstCharacter(str){
    return str.slice(0, 1);
}

function midCharacter(str){
    console.log(str.slice(1, -1), str)
    return str.slice(1, -1);
}

function lastCharacter(str){
    return str.slice(-1);
}

function isPalindrome(str){
    if (firstCharacter(str) !== lastCharacter(str)) return false;
    if (midCharacter(str).length <= 1) return true;

    return isPalindrome(midCharacter(str))
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€