-
[프로그래머스] 문자열 압축Engineering WIKI/Programmers 2022. 5. 2. 22:02
코딩테스트 연습 - 문자열 압축
데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문
programmers.co.kr
다른사람 풀이 (성공)
def solution(s): answer = len(s) # 1개 단위(step)부터 압축 단위를 늘려간다. for step in range(1, len(s) // 2 + 1): compressed = '' prev = s[:step] # 앞에서부터 step만큼의 문자열 출력 count = 1 # 단위 크기 만큼 증가시키며, 이전 문자열과 비교 for j in range(step, len(s), step): # 이전 횟수와 동일하면, 압축 횟수(count) 증가 if prev == s[j:j + step]: count += 1 # 다른 문자열이 나오면 else: compressed += str(count) + prev if count >= 2 else prev prev = s[j : j + step] # 다시 초기화 count = 1 # 남아 있는 문자열에 대해서 처리 compressed += str(count) + prev if count >= 2 else prev # 만들어지는 문자열이 가장 짧은 것이 정답 answer = min(answer, len(compressed)) return answer
다른방법 1
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, int(len(text)/2) + 1)) + [len(text)]) a = [ "aabbaccc", "ababcdcdababcdcd", "abcabcdede", "abcabcabcabcdededededede", "xababcdcdababcdcd", 'aaaaaa', ] for x in a: print(solution(x))
'Engineering WIKI > Programmers' 카테고리의 다른 글
[프로그래머스] 행렬 테두리 회전하기 (0) 2022.05.10 [프로그래머스] 타겟넘버 (0) 2022.05.06 [프로그래머스] 124 나라의 숫자 (0) 2022.05.04 [프로그래머스] 오픈채팅방 (0) 2022.05.02 [프로그래머스] 직사각형 별찍기 (0) 2022.05.01 [프로그래머스] x만큼 간격이 있는 n개의 숫자 (0) 2022.04.30 [프로그래머스] 행렬의 덧셈 (0) 2022.04.30 [프로그래머스] 핸드폰 번호 가리기 (0) 2022.04.29