문자열 압축

백승호·2021년 5월 6일
0

알고리즘공부

목록 보기
6/6
def compress(s, l):
    i = 0
    words = []
    while i < len(s):
        j = 0
        tmp = ""
        while j < l and i < len(s):
            tmp += s[i]
            j += 1
            i += 1
        words.append(tmp)
    i = 0
    cnt = 0
    while i < len(words):
        j = i + 1
        while j < len(words):
            if words[i] == words[j]:
                j += 1
            else:
                break ;
        tmp = j - i - 1
        if tmp >= 1 and tmp < 10:
            cnt = cnt + 1 + len(words[i])
        elif tmp >= 10 and tmp < 100:
            cnt = cnt + 2 + len(words[i])
        elif tmp >= 100 and tmp < 1000:
            cnt = cnt + 3 + len(words[i])
        else:
            cnt = cnt + len(words[i])
        if tmp >= 1:
            i = j
        else:
            i += 1
    return cnt

def solution(s):
    answer = 0
    max_len = len(s)
    if max_len == 0:
        return 0
    answer = 1001
    while max_len > 0:
        tmp = compress(s, max_len)
        if tmp < answer:
            answer = tmp
        max_len -= 1
    return answer

두문제에서 나가리..
내가 생각한 로직은
특정 길이만큼 요소가 나뉘어진 리스트를 만들고
리스트 요소를 돌면서 비교해가며 압축될 문자열의 길이를 구해나가는 것
이때 주의할건 두자릿수 세자릿수의 압축숫자가 나올수있다는것

다른사람풀이
참고: https://velog.io/@tjdud0123/%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%95%95%EC%B6%95-2020-%EC%B9%B4%EC%B9%B4%EC%98%A4-%EA%B3%B5%EC%B1%84-python

1~최대길이까지 압축시 길이 값 담는 리스트 만들고 그중 최소값 리턴하는 로직
문자열 쪼갠 리스트 만들때 slicing과 for in range()사용

profile
삽질하는 개발자 지망생

0개의 댓글