본문 바로가기
Algorithm/프로그래머스

[프로그래머스] - 압축 (파이썬)

by 2HS 2022. 2. 6.
alpha = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,
'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,
'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}

def solution(msg):
    answer = []
    left, right = 0, 1
    start = 0
    while right <= len(msg):
        temp = msg[left:right]
        if temp in alpha:
            if start != 0:
                answer.pop()
            answer.append(alpha[temp])
            right += 1
            start += 1
        else:
            alpha[temp] = len(alpha)+1
            left += len(temp)-1
            start = 0

    return answer

 

2018 카카오 블라인드 3차 - 2번

1. 알파벳을 딕셔너리로 정의해준다

2. left와 right으로 msg를 슬라이싱 해준다(temp)

    - temp가 alpha에 있고, 처음이라면 그냥 alpha[temp] append, right+=1, start+=1(start는 처음인지 확인하는 변수)

    - temp가 alpha에 있고, append를 했었으면 pop먼저 해주고 진행

    - temp가 alpha에 없으면 alpha에 새로운 값을 넣어주고 left += len(temp)-1, start = 0

3. answer 출력