기억은 짧고 기록은 길다
[프로그래머스/Programmers] 문자열 압축 - Python 본문
Link
코딩테스트 연습 - 문자열 압축
데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문
programmers.co.kr
Solution
def solution(s):
lens = []
if len(s) == 1:
return 1
compact = ''
for i in range(1, len(s) // 2 + 1):
count = 1
t = s[:i]
for j in range(i, len(s), i):
if s[j:j + i] == t:
count += 1
else:
if count == 1:
count = ''
compact += str(count) + t
t = s[j: j + i]
count = 1
if count == 1:
count = ''
compact += str(count) + t
lens.append(len(compact))
compact = ''
return min(lens)
🔑 key point:
for j in range(i, len(s), i):
if s[j:j + i] == t:
count += 1
else:
if count == 1:
count = ''
compact += str(count) + t
t = s[j: j + i]
count = 1
Other Solution
def compress(text, tok_len):
words = [text[i:i + tok_len] for i in range(0, len(text), tok_len)]
res = []
cur_word = words[0]
cur_cnt = 1
for a, b in zip(words, words[1:] + ['']):
if a == b:
cur_cnt += 1
else:
res.append([cur_word, cur_cnt])
cur_word = b
cur_cnt = 1
return sum(len(word) + (len(str(cnt)) if cnt > 1 else 0) for word, cnt in res)
def solution(text):
return min(compress(text, tok_len) for tok_len in list(range(1, len(text) // 2 + 1)) + [len(text)])
'CodingTest > programmers' 카테고리의 다른 글
[프로그래머스/Programmers] 숫자의 표현 - Python (0) | 2021.09.17 |
---|---|
[프로그래머스/Programmers] 방문 길이 - Python (0) | 2021.09.17 |
[프로그래머스/Programmers] 땅 따먹기 - Python (0) | 2021.09.16 |
[프로그래머스/Programmers] 더 맵게 - Python (0) | 2021.09.16 |
[프로그래머스/Programmers] 다음 큰 숫자 - Python (0) | 2021.09.15 |
Comments