본문 바로가기

problem solving

[프로그래머스]조이스틱

우선 A로 이루어진 name의 길이만큼의 문자열(str)을 만든다.

정답을 도출하기위해 그리디 기법을 사용했는데,

두 개의 반복문으로 우측과 좌측으로 각각 순회한다.

이 때 str과 name의 문자가 같을 때 이동횟수를 추가해준다. (str[0] == 'A' && name == 'A')

문자가 다르다면 반복문을 탈출해주고 pos변수에  탈출할 때까지의 이동횟수를 넣어주는데

왼쪽과 오른쪽중 적게 이동한 곳의 위치를 넣는다.

(만약 str과 name이 모두 같은 문자라면  현재까지의 count값을 반환한다)

위치를 갱신하고 거기까지 이동한 횟수를 count에 더하고,

현 위치의 str과 name의 문자값의 가장 적은 차이(역순으로의 개수를 셀 때 크기가 더 작을 수 있다)만큼 count에 더해준다.

#include <string>
#include <vector>
#include <cmath>
 
using namespace std;
 
int solution(string name) {
    int answer = 0;
    
    string str = "";
    for(int a : name) {
        str += "A";
    }
    
    int right, rCnt, left, lCnt;
    int pos = 0;
    while (true) {
        right = pos, left = pos;
        rCnt = lCnt = 0;
        for(int j = 0; j < name.size(); j++) {
            if(str[right] == name[right]) {
                right++;
                rCnt++;
                if(right == name.size()) {
                    right = 0;
                }
            }
            else {
                break;
            }
            
            if(j == name.size() - 1) { return answer;}
        }
        for(int j = 0; j < name.size(); j++) {
            if(str[left] == name[left]) {
                left--;
                lCnt++;
                if(left == -1) {
                    left = name.size() - 1;
                }
            }
            else {
                break;
            }
            
            if(j == name.size() - 1) { return answer;}
        }
        pos = rCnt < lCnt ? left : right;
        
        if(rCnt < lCnt) { answer += rCnt; }
        else { answer += lCnt; }
        int gap = str[pos] - name[pos];
        answer += abs(gap) > abs(gap) * -1 + 26 ? abs(gap) * -1 + 26 : abs(gap);
        
        str[pos] = name[pos];
    }
    
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]큰 수 만들기  (0) 2020.03.09
[프로그래머스]가장 큰 수  (0) 2020.03.09
[프로그래머스]컬러링북  (0) 2020.03.08
[프로그래머스]문자열 압축  (0) 2020.03.07
[프로그래머스]프린터  (0) 2020.03.07