문제
제한 사항
입출력 예
풀이
function count(n) {
let cnt = 0;
if (n < 78) {
cnt += n % 65;
} else {
cnt += 91 - n;
}
return cnt;
}
const solution = (name) => {
let answer = 0;
let min = name.length - 1;
for (let i = 0; i < name.length; i++) {
let cur = name.charCodeAt(i);
answer += count(cur);
let nextIndex = i + 1;
while (nextIndex < name.length && name.charCodeAt(nextIndex) === 65) {
nextIndex++;
}
min = Math.min(min, i * 2 + name.length - nextIndex);
min = Math.min(min, (name.length - nextIndex) * 2 + i);
}
answer += min;
return answer;
};
- 그리디라고 하기엔 애매한 것 같다.
- 오락실 게임에서 순위를 갱신하면 이름을 남기는 것과 같게 생각하면 된다.
- count 함수는 알파벳을 A에서 얼마나 이동시켜주는지 세어주는 함수이다. 조건문의 기준인 78은 알파벳 중 가운데인 N의 아스키 코드 값이다.
- 이 문제의 어려운 점은 커서를 이동할 최소 값을 찾는 방법이다. 반복문을 통해 nextIndex의 값은 연속되는 A를 모두 지나친 A가 아닌 알파벳의 인덱스 값이다. 연속된 A의 수가 많아서 뒤에서부터 이동하는 케이스가 최소 값이 될 수 있기 때문에
i * 2 + name.length - nextIndex
형태가 나온 것인데 자세한 것은 주석을 살펴보자.
- 아예 뒤에를 먼저 바꾸고 오는게 짧을 수도 있기 때문에
(name.length - nextIndex) * 2 + i
도 비교 대상이 된다.
다른 코드
function count(n) {
let cnt = 0;
if (n < 78) {
cnt += n % 65;
} else {
cnt += 91 - n;
}
return cnt;
}
function solution(name) {
let answer = 0;
let cursorCountList = [name.length - 1];
for (let i = 0; i < name.length; i++) {
answer += count(name.charCodeAt(i));
}
for (let j = 0; j < name.length; j++) {
let endOfA = j + 1;
while (endOfA < name.length && name[endOfA] === "A") {
endOfA++;
}
cursorCountList.push(j * 2 + name.length - endOfA);
cursorCountList.push((name.length - endOfA) * 2 + j);
}
answer += Math.min(...cursorCountList);
return answer;
}