[프로그래머스] 문자열 압축

Narcoker·2023년 5월 10일
0

코딩테스트

목록 보기
97/150

문제

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

풀이

자르는 길이를 기준으로 입력값을 자른다.
만약 처음 자른 단어이거나 key 배열의 맨뒤의 값, 즉 전 단어와 다르다면
key에 해당 단어를 넣고 count에 1을 넣는다.

만약 전 단어와 같다면
전단어의 반복 횟수인 count[-1]의 값을 1 증가 시킨다.

이 작업을 마치면
key에 들어있는 단어들의 길이 합과
count에 들어있는 숫자들을 문자열로 바꾼 후
그 문자열의 길이를 모두 더한 값을 더한다.

이 값이 answer와 비교하여 더 작은 값으로 재할당한다.

from functools import reduce
def solution(s):
    answer = 100000

    for unit in range(1, len(s)+1): # 자르는 길이 설정
        key = []
        count = []
        for start in range(0, len(s), unit):
            word = s[start:start+unit]

            if start == 0 or word != key[-1]:
                key.append(word)
                count.append(1)

            elif word == key[-1]:
                count[-1] += 1

        len_key = reduce(lambda acc, value : acc+len(value), key, 0)
        len_count = reduce(lambda acc, value: acc + (len(str(value)) if value != 1 else 0), count, 0)

        answer = min(answer, len_key + len_count)
    return answer
profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글