728x90
반응형

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

 

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

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

programmers.co.kr

 

* 2020 KAKAO BLIND RECRUITMENT 문제 

 

def solution(s):
cand = [len(s)]
for i in range(1, len(s)): #size
split = [s[j:j+i] for j in range(0,len(s),i)]
cnt = 1
res = ""
# check duplicate
for k in range(1,len(split)): #0-7
prev, cur = split[k-1], split[k]
if prev == cur:
cnt += 1
else:
if cnt > 1:
res += (str(cnt) + prev)
else:
res += prev
cnt = 1
if cnt > 1:
res += (str(cnt) + split[-1])
else:
res += split[-1]
cand.append(len(res))
return min(cand)

 

+ 구글링 하다보니 groupby라는 함수를 찾아서 사용해봤다..!

Python Itertools 의 groupby 함수 사용한 버전 => 효율성 테스트 하는 경우에는 안쓰는 것이 적합!

from itertools import groupby
def solution(s):
cand = [len(s)]
for i in range(1, len(s)): #size
split = [s[j:j+i] for j in range(0,len(s),i)]
cnt = 1
res = ""
for k, g in groupby(split):
dup = list(g)
if len(dup) > 1:
res += str(len(dup)) + k
else:
res += k
# print(res)
cand.append(len(res))
return min(cand)

 

728x90
반응형