#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
 
int solution(string name) 
{
    int answer = 0;
    string start;
    
    for(int i = 0; i < name.size(); i++)
    {
        start += "A";
    }
    
    int nowIdx = 0;
    while(1)
    {   
        answer += min(name[nowIdx] - 'A''Z' - name[nowIdx] + 1);
        start[nowIdx] = name[nowIdx];
        
        if(start == name)
        {
            return answer;
        }
        
        // 1. 왼쪽 이동 횟수 구하기
        int leftIdx = nowIdx;
        int leftCnt = 0;
        
        while(start[leftIdx] == name[leftIdx])
        {
            leftIdx--;
            leftCnt++;
            
            // 왼쪽으로 이동시에 범위를 벗어나는 경우
            if(leftIdx == -1)
            {
                leftIdx = name.size()-1;
            }
        }
        
        // 2. 오른쪽 이동 횟수 구하기
        int rightIdx = nowIdx;
        int rightCnt = 0;
        
        while(start[rightIdx] == name[rightIdx])
        {
            rightIdx++;
            rightCnt++;
            
            // 오른쪽으로 이동시에 범위를 벗어나는 경우
            if(rightIdx == name.size())
            {
                rightIdx = 0;
            }      
        }
        
        // 3. 왼쪽, 오른쪽 중 횟수가 최소인 방향을 선택
        // 왼쪽 선택
        if(leftCnt < rightCnt)
        {
            answer += leftCnt;
            nowIdx = leftIdx;
        }
        // 오른쪽 선택
        else
        {
            answer += rightCnt;
            nowIdx = rightIdx;
        }
    }
}
cs

+ Recent posts