조이스틱_복습2

하이솝·2026년 10월 8일

코테 · Greedy

목록 보기
6/7

2026.10.08

문제 풀이

나의 코드

소요 시간: 1시간 20분
시간 복잡도: O(L2)O(L^2) (L은 name의 길이)

import java.util.List;
import java.util.ArrayList;

class Solution {
    public int solution(String name) {
        int len = name.length();
        int cntAlpha = 0;
        List<Integer> list = new ArrayList<>();
        list.add(0); // 최초 시작 위치 저장
        for (int i = 0; i < len; i++) {
            char c = name.charAt(i);
            if (c != 'A') {
                if (c < 'N') {
                    cntAlpha += c - 'A';
                } else {
                    cntAlpha += 'Z' - c + 1;
                }
                if (!list.contains(i)) list.add(i);
            }
        }
        int cntMove = Integer.MAX_VALUE;
        for (int i = 0; i < list.size() - 1; i++) {
            int a = list.get(i);
            int b = list.get(i + 1);
            int move = (a * 2) + (len - b);
            cntMove = Math.min(cntMove, move);
        }
        cntMove = Math.min(cntMove, list.get(list.size() - 1));
        for (int i = list.size() - 1; i > 0; i--) {
            int a = list.get(i);
            int b = list.get(i - 1);
            int move = ((len - a) * 2) + b;
            cntMove = Math.min(cntMove, move);
        }
        
        return cntAlpha + cntMove;
    }
}

AI 코드

시간 복잡도: O(L2)O(L^2) (L은 name의 길이)

class Solution {
    public int solution(String name) {
        int len = name.length();
        int answer = 0;
        
        for (int i = 0; i < len; i++) {
            char c = name.charAt(i);
            answer += Math.min(c - 'A', 'Z' - c + 1);
        }
        
        int move = len - 1;
        for (int i = 0; i < len; i++) {
            int next = i + 1;
            while (next < len && name.charAt(next) == 'A') next++;
            move = Math.min(move, i * 2 + (len - next));
            move = Math.min(move, (len - next) * 2 + i);
        }
        return answer + move;
    }
}

문제 풀이 후기

문제를 풀긴 풀었지만, 이미 풀어봤던 문제라 이전의 기억에 기대서 풀었다.

Level 2밖에 되지 않지만
정답률이 40%대로 낮은 문제로 난이도가 꽤나 있는 문제다.

앞으로 이런 문제들을 처음 풀어볼 때에도 풀 수 있도록 많은 연습이 필요하다.

0개의 댓글