KEEP GOING

[python] 프로그래머스 60057번 : 문자열 압축 (slicing) 본문

code review/implementation

[python] 프로그래머스 60057번 : 문자열 압축 (slicing)

jmHan 2022. 1. 7. 21:39
반응형

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

 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문

programmers.co.kr

 

 

1. 정답인 코드

def solution(s):
    answer = 1001
    n = len(s)
    # 테스트케이스 5번 : 문자열 s의 길이가 1일때 처리 
    if n == 1:
        return 1
    for unit in range(1, n//2+1):
        # print('unit=', unit)
        compress = ""
        pre = s[0:unit]
        # print('pre',pre)
        count = 1
        # 단위(unit)만큼 크기 증가시켜 비교
        for i in range(unit, n, unit):
            if pre == s[i:i+unit]:
                # print('yes')
                count += 1
            else:
                # 중복 카운팅이 2이상인 경우에만 숫자 포함 
                compress += str(count) + pre if count >= 2 else pre 
                pre = s[i:i+unit]
                count = 1
                # print('compress', compress, end = ' ')
                # print('pre',pre)
        # else 문에 걸리지 않아 compress에 포함되지 않은 문자열 처리 
        compress += str(count) + pre if count >= 2 else pre
        # print('compress', compress)
        answer = min(answer, len(compress))
    return answer
반응형
Comments