๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Javascript] ๋ฌธ์ž์—ด ๋ฐ€๊ธฐ || ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

728x90

<ํ‹€๋ฆฐ ๋‹ต>

function solution(A, B) {
    const aArr = A.split("");
    const bArr = B.split("");
    // console.log(aArr, bArr)    //[ 'h', 'e', 'l', 'l', 'o' ] [ 'o', 'h', 'e', 'l', 'l' ]
    let matchIndex = [];
    for (let i = 0; i < aArr.length; i++) {
        aArr[0] === bArr[i] && matchIndex.push(i);
    }
    console.log(matchIndex);
    let result = 0;
    matchIndex.sort((a, b) => b - a).map(index => {
        let cArr = new Array(aArr.length);
        aArr.map((v, i) => i + index >= A.length ? cArr[i + index - aArr.length] = v : cArr[i + index] = v)
        console.log("cArr", cArr);
        if (cArr.join("") === bArr.join("")) {
            result = index;
            return;
        } else {
            result = -1;
        }
    })
    console.log("result", result);
    return result;
}

solution("hello", "ohell");
solution("apple", "elppa");
solution("atat", "tata");
solution("abc", "abc");
solution("abcabc", "bbbaaa")

๋ฐฐ์—ด์—์„œ ๋งž๋Š” index ๊ตฌํ•ด์„œ, ๊ทธ index ๋ฐฐ์—ด์—์„œ ํฐ ์ˆ˜๋ถ€ํ„ฐ ๋น„๊ต -> ์ž‘์€ ์ˆ˜๊ฐ€ ๋‚˜์˜ค๋ฉด result ๋ฅผ ๋ฎ์–ด์”Œ์šฐ๋„๋ก ๋งŒ๋“ค์—ˆ๋‹ค.

ํ…Œ์Šคํฌ ์ฝ”๋“œ ํ†ต๊ณผ๋Š” ์ž˜ ํ–ˆ๋Š”๋ฐ ๋งˆ์ง€๋ง‰์— ํ†ต๊ณผ ๋ชปํ•ด์„œ ๋ญ˜๊นŒ ๊ณ ๋ฏผํ–ˆ์Œ.

 

 

๋ฐฐ์—ด๋กœ ๋ฐ”๊ฟ”์„œ ์™œ ์•ˆ๋˜์ง€ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ๋‹ค๋ฅธ ๋ธ”๋กœ๊ทธ๋ฅผ ์ฐธ๊ณ ํ•ด๋ณด๊ธฐ๋กœ ํ–ˆ๋‹ค.

 

<์ •๋‹ต>

function solution(A, B) {
    let arr = [...A]
    for(let i = 0; i< arr.length; i++){
        if(A === B)
            return i;
        else{
            arr.unshift(arr.pop())
            if(arr.join('') === B)
                return i+1;
        }
    }
    return -1;
}

์˜ค.. 

๊ทธ๋ƒฅ string ์œผ๋กœ๋„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๊ตฌ๋‚˜ ๊ฐํƒ„ํ–ˆ๋Š”๋ฐ

 

let solution=(a,b)=>(b+b).indexOf(a)

.....?????

 

์•„๋‹ˆ???

 

์ด๋ ‡๊ฒŒ ๊ฐ„๋‹จํžˆ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค๋‹ˆ,,,

 

์—ญ์‹œ ๋ณต์žกํ•œ ๋ฌธ์ œ์ผ ์ˆ˜๋ก ๊ฐ„๋‹จํžˆ ๋ณผ ์ˆ˜ ์žˆ๋Š”๊ฒŒ ์ตœ๊ณ ์ธ ๋“ฏ ํ•˜๋‹ค,,,

 

 

728x90
๋ฐ˜์‘ํ˜•