๋ณธ๋ฌธ์œผ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

42860. ์กฐ์ด์Šคํ‹ฑ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์กฐ์ด์Šคํ‹ฑ


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
ํƒ์š•๋ฒ•(๊ทธ๋ฆฌ๋””)lv.21์‹œ๊ฐ„ 30๋ถ„โœ…

์„ค๊ณ„ ๋ฐฉ๋ฒ•#

  • A๊ฐ€ ์•„๋‹Œ ์œ„์น˜(๋ฐฉ๋ฌธํ•ด์•ผํ•  ์œ„์น˜)์˜ index ๋“ค์„ Map ์ž๋ฃŒ๊ตฌ์กฐ์— ๋‹ด๋Š”๋‹ค. positions

  • ๋ฐ˜๋ณต๋ฌธ

    • ๋ฐฉ๋ฌธํ•  ์œ„์น˜์˜ ์ตœ์†Œ ์•ŒํŒŒ๋ฒณ ์ด๋™ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•ด์„œ move ์— ๋”ํ•œ๋‹ค. (range ํ•จ์ˆ˜๋ฅผ๋งŒ๋“ค์–ด ์ผ๋Š”๋ฐ, ๋‹ค์‹œ๋ณด๋‹ˆ ๋ถˆํ•„์š”ํ•œ ์ฝ”๋“œ์ธ ๋“ฏ)

    • ํ˜„์žฌ ์œ„์น˜๋ฅผ ๋ฐฉ๋ฌธํ•œ ๊ฒƒ์œผ๋กœ ์ฒ˜๋ฆฌ. positions.delete

    • ๋ฐฉ๋ฌธํ•  ์œ„์น˜๊ฐ€ ๋‚จ์•„์žˆ์ง€ ์•Š์œผ๋ฉด ๋ฐ˜๋ณต๋ฌธ ์ข…๋ฃŒ

    • positions ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ์œ„์น˜๋ฅผ ์ฐพ๋Š”๋‹ค.

    • ํ•ด๋‹น ์œ„์น˜๋กœ ์ด๋™ํ•˜๊ณ  ์ด๋™ํ•œ ๋งŒํผ move ์— ๋”ํ•œ๋‹ค.

์ฝ”๋“œ#

function solution(name) {    const dirties = [...name].map((ch) => ch !== 'A');    const positions = dirties.reduce(        (map, cur, i) => (cur ? new Map([...map, [i, i]]) : map),        new Map(),    );
    const length = name.length;    let curPosition = 0;    let move = 0;
    while (true) {        move += findLeastAlphabetMove(name[curPosition]);        positions.delete(curPosition);
        if (!positions.size) {            break;        }
        let leastDistance = length;        let nextPosition = curPosition;
        positions.forEach((position) => {            const distance = Math.min(                Math.abs(curPosition + length - position),                Math.abs(position - curPosition),            );
            if (distance < leastDistance) {                leastDistance = distance;                nextPosition = position;            }        });
        curPosition = nextPosition;        move += leastDistance;    }
    return move;}
const range = (start, stop, step) =>    Array.from({length: (stop - start) / step + 1}, (_, i) => start + i * step);
const findLeastAlphabetMove = (target) => {    const alphabets = new Map(        range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1)            .map((x) => String.fromCharCode(x))            .map((v, i) => [v, i]),    );
    const targetPosition = alphabets.get(target);
    return alphabets.size / 2 > targetPosition        ? targetPosition        : alphabets.size - targetPosition;};

์‹œ๊ฐ„ ๋ณต์žก๋„#

  • A๊ฐ€ ์•„๋‹Œ ์œ„์น˜ ๊ฐœ์ˆ˜ (N)

  • O(N!)

์–ด๋ ค์› ๋˜ ์ #

  • ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์•„์ง ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค..

  • ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ ์˜ค๋ฅธ์ชฝ์œผ๋กœ๋งŒ ๊ฐ€๋Š” ๊ฒฝ์šฐ, ์™ผ์ชฝ์œผ๋กœ๋งŒ ๊ฐ€๋Š” ๊ฒฝ์šฐ, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๊ฐ”๋‹ค๊ฐ€ ์™ผ์ชฝ์œผ๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ, ์™ผ์ชฝ์œผ๋กœ ๊ฐ”๋‹ค๊ฐ€ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด์„œ ํ’€์—ˆ๋Š”๋ฐ, ์ด ํ’€์ด๋ฅผ ๋– ์˜ฌ๋ฆฌ๊ธฐ๋Š” ์–ด๋ ค์› ๋‹ค.

์ฐธ๊ณ ์ž๋ฃŒ#

LIBRARY : ๋„ค์ด๋ฒ„ ๋ธ”๋กœ๊ทธ