나의 풀이
- 주어진 문자열 길이가 1이면 1을 반환한다.
- 문자열을 가장 길게 압축하는 길이는 문자열 절반 길이이다.
- 주어진 문자열을 1부터 문자열 절반 길이까지 압축한다.
- 주어진 문자열을 특정 간격으로 자른다.
- 자른 문자열을 비교하여 압축한다.
- 압축한 문자열의 길이를 담은 리스트(
length_list
)에 모든 압축한 문자열의 길이를 담는다. length_list
의 최솟값을 구한다.
def solution(string):
length_list = []
string_length = len(string)
if string_length == 1:
return 1
for compress_length in range(1, string_length // 2 + 1):
length_list.append(
len(compress_string_by_length(string, compress_length, string_length))
)
return min(length_list)
def compress_string_by_length(string, compress_length, string_length):
compressed_string = ""
splited_string = split_string_by_length(string, compress_length, string_length)
duplicated_count = 1
for i in range(len(splited_string)):
if i < len(splited_string) - 1 and splited_string[i] == splited_string[i + 1]:
duplicated_count += 1
else:
if duplicated_count == 1:
compressed_string += splited_string[i]
else:
compressed_string += str(duplicated_count) + splited_string[i]
duplicated_count = 1
return compressed_string
def split_string_by_length(string, compress_length, string_length):
return [
string[i : i + compress_length]
for i in range(0, string_length, compress_length)
]
'프로그래밍-학습기록 > 코딩테스트' 카테고리의 다른 글
프로그래머스 | level 1 | python | 3진법 뒤집기 (0) | 2021.03.01 |
---|---|
프로그래머스 | 파이썬 | 삼각달팽이 (0) | 2020.12.29 |
프로그래머스 | python | 괄호 변환 | 용기의 문제 (0) | 2020.12.24 |
프로그래머스 | python | 스킬트리 (0) | 2020.12.23 |
프로그래머스 | python | level 2 | 올바른 괄호 (0) | 2020.12.22 |