[알고리즘] 프로그래머스 2단계 문자열 압축

minidoo·2020년 10월 26일
0

알고리즘

목록 보기
48/85
post-thumbnail
def solution(s):
    
    lenS = len(s)
    num = 1
    result = []
    
    if lenS == 1:
        return 1
    
    while True:
        stack = []
        for i in range(0, lenS):
            if i % num == 0:
                stack.append(s[i:i+num])
        
        if len(stack) == len(s):
            result.append(stack)
    
        if len(stack) != 1:
            result.append(stack)
                
        num += 1   
        if num == lenS + 1 :
            break
            
    kikiki = 1000
    for answer in result:
        new = []
        index = 0
        k = 0
        while True:
            if answer[index] == answer[index+1]:
                index += 1

            else:
                new.append(answer[k:index+1])
                k = index + 1
                index += 1

            if index == len(answer)-1:
                new.append(answer[k:index+1])
                break

        new_str = ''
        for n in new:
            if len(n) != 1:
                new_str += str(len(n))
            new_str += str(n[0])
        
        if len(new_str) < kikiki:
            kikiki = len(new_str)
    
    return kikiki

입출력 예

풀이과정

  1. aabbaccc를 1개, 2개 ... 8개 단위로 자른다. 예를 들어 1개를 기준으로 자른다고 했을 때, 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'c'가 stack에 담기고 이를 다시 result에 담는다.
  2. num이 문자열의 길이 + 1가 되면 while문을 빠져나온다.
  3. result에 담긴 배열 각각을 answer라고 한다. 만약 answer가 ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'c']라면 반복문을 돌면서 index와 index+1이 같은 것을 묶어 준다. 해당 예시에서 new에는 [['a', 'a'], ['b', 'b'], ['a'], ['c', 'c', 'c']]이 담긴다.
  4. new_str은 2a2ba3c가 된다. s의 길이는 1000이하임으로 kikiki에 s의 길이를 할당하고, 만약 new_str의 길이가 kikiki보다 작다면 new_str을 할당한다.

0개의 댓글