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

IT공부중·2020년 4월 9일
0

알고리즘

목록 보기
11/49

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

def checkEqual(text, index, count, now): # 문자열에서 어디부터 몇개씩..
    if count + index>= len(text): # 마지막일경우
        return [now, text[index: index+count], index+count]

    if text[index:index+count] != text[index+count: 2* count + index]: # 다를 경우
        return [now, text[index:index+count], index+count] # 문자열반환, 
    
    now += 1
    [now, tempText, tempIndex] = checkEqual(text, count + index, count, now)
    return [now, tempText, tempIndex]

def solution(s):
    minLength = len(s)
    totalLength = len(s)
    
    for count in range(1, (len(s) // 2) + 1):
        resultText = ''
        index = 0
        while index <= len(s):
            now = 1
            if index + count >= len(s):
                resultText += s[index:]
                break
            [now, tempText, index] = checkEqual(s, index, count, now)
            if(now == 1):
                resultText += tempText
            else:
                resultText += (str(now) + tempText)
        if resultText != '':
            minLength = min(minLength, len(resultText))

    return minLength

가운데까지 해서 압축이 되지 않는다면 어차피 그 뒤에는 압축이 안 될거니깐 가운데까지를 기준으로 잡았다.
현재 index에서 count늘린 만큼이 문자열을 넘으면 그냥 result에 추가해줬고 안 넘을시에는 checkEqual 함수를 실행해서 [몇번 반복되었는지, 어떤 문자가 반복되었는지, 몇번 index까지 갔는지]를 반환해주도록 했다.

checkEqual은 반복되는지의 여부를 판단하여 반복이 안 될때까지 재귀적으로 확인하는 함수이다.

결과를 나온 함수를 길이를 비교해서 minLength로 만든다. 끝까지 한 후 minLength를 반환하게 만들었다.

profile
3년차 프론트엔드 개발자 문건우입니다.

0개의 댓글