2020 카카오 인턴쉽 - 키패드 누르기 (Level 1)

 

https://programmers.co.kr/learn/courses/30/lessons/67256


Code

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
def solution(numbers, hand):
    def dist(last_hand, number):
        def number2index(number):
            if number == '*':
                return 3, 0
            elif number == '#':
                return 3, 2
            elif number == 0:
                return 3, 1
            else:
                return (number-1) // 3, (number-1) % 3
        h1, h2 = number2index(last_hand)
        n1, n2 = number2index(number)
        return abs(h1-n1) + abs(h2-n2)

    left, right  = '*', '#'
    table = {'left': 'L', 'right': 'R'}

    answer = ''
    for number in numbers:
        if number in [1, 4, 7]:
            left = number
            last_hand = 'left'
        elif number in [3, 6, 9]:
            right = number
            last_hand = 'right'
        else:
            d = dist(left, number) - dist(right, number)
            if d == 0:
                if hand == 'right':
                    right = number
                else:
                    left = number
                last_hand = hand
            elif d > 0:
                right = number
                last_hand = 'right'
            else:
                left = number
                last_hand = 'left'
        answer = f"{answer}{table[last_hand]}"
    return answer

Complexity

$O(|\text{numbers}|)$