신재권 2023. 3. 31. 17:24
package programmers;

public class 조이스틱 {

/*
   ▲ - 다음 알파벳
   ▼ - 이전 알파벳 (A에서 아래쪽으로 이동하면 Z로)
   ◀ - 커서를 왼쪽으로 이동 (첫 번째 위치에서 왼쪽으로 이동하면 마지막 문자에 커서)
   ▶ - 커서를 오른쪽으로 이동 (마지막 위치에서 오른쪽으로 이동하면 첫 번째 문자에 커서)
*/

   public static int solution(String name) {

      int answer = 0;
      int len = name.length();

      int idx;
      int move = len - 1;

      for (int i = 0; i < name.length(); i++) {
         answer += Math.min(name.charAt(i) - 'A', 'Z' - name.charAt(i) + 1);
         idx = i + 1;

         //연속되는 A 갯수 확인
         while (idx < len && name.charAt(idx) == 'A') {
            idx++;
         }

         //순서대로 가기 vs 오른쪽으로 갓다가 A를 만나면 왼쪽으로 가기 vs 왼쪽으로 갓다가 A를 만나면 오른쪽으로 가기
         int rightAndLeft = i * 2 + len - idx;
         int leftAndRight = (len - idx) * 2 + i;
         move = Math.min(move, Math.min(rightAndLeft, leftAndRight));
      }

      return answer + move;
   }

   public static void main(String[] args) {
      System.out.println(solution("JAZ") == 11);
      System.out.println(solution("BAAAAABB") == 5);
      System.out.println(solution("BABB") == 5);
      System.out.println(solution("JEROEN") == 56);
      System.out.println(solution("JAN") == 23);
   }
}