1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
class Solution
{
    public int solution(string name)
    {
        int moveCount = 0;
 
        // n은 입력 문자열 name의 길이를 나타낸다.
        int nameLength = name.Length;
 
        // leftOrRight는 왼쪽 또는 오른쪽으로 이동할 경우의 최소 이동 횟수를 저장한다.
        int minLeftRightCount = name.Length - 1;
 
        // 문자열의 각 문자에 대해 반복문을 실행한다.
        for (int i = 0; i < nameLength; i++)
        {
            //다음 문자의 위치
            int next = i + 1;
 
            char target = name[i];
 
            if (target <= 'N')
            {
                //문자가 N이하라면, A에서 위로 이동하며 타겟 문자에 도달하는 것이 효율적이다.
                moveCount += target - 'A';
            }
            else
            {
                //문자가 'O'이상이라면, A에서 아래로 이동하며 타겟 문자에 도달하는 것이 효율적이다.
                moveCount += 'Z' - target + 1;
            }
 
            //현재 위치 이후의 문자 중에서 A가 아닌 첫 문자를 찾는다.
            while (next < nameLength && name[next] == 'A')
                next++;
 
            //A가 아닌 문자를 찾을 때, 좌 우 방향의 이동횟수를 구하고,
            int currentLeftRightCount = i + nameLength - next + Math.Min(i, nameLength - next);
 
            //최소값을 갱신한다.
            minLeftRightCount = Math.Min(minLeftRightCount, currentLeftRightCount);
        }
 
        //구한 좌우 방향 이동 최소값을 더한다.
        moveCount += minLeftRightCount;
 
        return moveCount;
    }
}
 
cs

+ Recent posts