42860. ์กฐ์ด์คํฑ
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ์กฐ์ด์คํฑ
๋ฌธ์ ์ ํ | ๋์ด๋ | ๊ฑธ๋ฆฐ ์๊ฐ | ํด๊ฒฐ ์ ๋ฌด(โ /โ) |
---|---|---|---|
ํ์๋ฒ(๊ทธ๋ฆฌ๋) | lv.2 | 1์๊ฐ 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!)
#
์ด๋ ค์ ๋ ์ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ์ ์์ง ์ ๋ชจ๋ฅด๊ฒ ๋ค..
๋ค๋ฅธ ํ์ด๋ฅผ ๋ณด๋ ์ค๋ฅธ์ชฝ์ผ๋ก๋ง ๊ฐ๋ ๊ฒฝ์ฐ, ์ผ์ชฝ์ผ๋ก๋ง ๊ฐ๋ ๊ฒฝ์ฐ, ์ค๋ฅธ์ชฝ์ผ๋ก ๊ฐ๋ค๊ฐ ์ผ์ชฝ์ผ๋ก ๊ฐ๋ ๊ฒฝ์ฐ, ์ผ์ชฝ์ผ๋ก ๊ฐ๋ค๊ฐ ์ค๋ฅธ์ชฝ์ผ๋ก ๊ฐ๋ ๊ฒฝ์ฐ๋ก ๋๋์ด์ ํ์๋๋ฐ, ์ด ํ์ด๋ฅผ ๋ ์ฌ๋ฆฌ๊ธฐ๋ ์ด๋ ค์ ๋ค.