honey_pot

[Python] [3차] 압축 본문

문제 풀이

[Python] [3차] 압축

_tera_ 2022. 9. 20. 12:42

https://school.programmers.co.kr/learn/courses/30/lessons/17684


현재 문자를 w, 다음 문자를 c로 두고 사전에 입력되어있으면 다음 문자에 해당하는 부분을 1씩 늘린다

사전에 없는 문자열이면 다음 문자가 될 마지막 문자를 제외한 앞 문자열(이전 루프에서 사전에 있는 것으로 판별됨)의 순서를 answer에 넣고 w를 c의 바로 전으로 이동시킨다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def solution(msg):
    answer = []
    dic = {}
    for i in range(65,91):
        dic[chr(i)] = i-64
    w,c = 0,1
    while True:
        word = msg[w:c]
        if c == len(msg)+1:
            answer.append(dic[word])
            return answer
        if word in dic:
            c += 1
        else:
            answer.append(dic[word[:-1]])
            dic[word] = max(dic.values())+1
            w = c-1
    return answer
            
cs

 

다른  풀이를 찾아보니 c를 맨 마지막에서 시작해서 점점 줄이는 방식도 있었다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def solution(msg):
    answer = []
    dic = {}
    for i in range(65,91):
        dic[chr(i)] = i-64
    w,c = 0,len(msg)
    while True:
        word = msg[w:c]
        if word in dic.keys():
            answer.append(dic[word])
            if c >= len(msg):
                return answer
            dic[word + msg[c]] = max(dic.values())+1
            w += len(word)
            c = len(msg)
        else:
            c -= 1
    return answer
            
cs
Comments