[프로그래머스 Level 2] 조이스틱
1분 읽기
풀이 1:
function solution(name) {
const A = 'A'.charCodeAt();
const Z = 'Z'.charCodeAt();
const n = name.length;
const { total, move } = [...name].reduce((acc, current, i) => {
let next = i + 1;
while (next < n && name[next] === 'A') next++;
// 1. 커서 조작
const move = Math.min(
acc.move, // 1-1. 좌우 단방향(initial)
i * 2 + (n - next), // 1-2. 우측 → 좌측 → 좌측
(n - next) * 2 + i // 1-3. 좌측 → 좌측 → 우측
)
// 2. 알파벳 조작
const total = acc.total + Math.min(
current.charCodeAt() - A, // 2-1. A → to
1 + Z - current.charCodeAt(), // 2-2. A → Z(via) → to
)
return { total, move };
}, { total: 0, move: n - 1 });
return total + move;
}Review
제한 사항
- name은 알파벳 대문자로만 이루어져 있습니다.
- name의 길이는 1 이상 20 이하입니다.
Greedy10편 중 1번째
관련 글
4분 읽기
소수 구하기
소수 판별법과 소수를 구하는 알고리즘을 정리합니다.
1분 읽기
[프로그래머스 Level 2] 미로 탈출
프로그래머스 미로 탈출을 BFS로 풀이합니다.
1분 읽기
[프로그래머스 Level 2] 마법의 엘리베이터
프로그래머스 마법의 엘리베이터를 자리수 그리디로 풀이합니다.