본문 바로가기
Algorithm

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

by YGSEO 2021. 3. 3.
728x90

다른 사람의 풀이

def solution(s):
    length = []
    result = ""
    
    if len(s) == 1:
        return 1
    
    for cut in range(1, len(s) // 2 + 1): 
        count = 1
        tempStr = s[:cut] 
        for i in range(cut, len(s), cut):
            if s[i:i+cut] == tempStr:
                count += 1
            else:
                if count == 1:
                    count = ""
                result += str(count) + tempStr
                tempStr = s[i:i+cut]
                count = 1

        if count == 1:
            count = ""
        result += str(count) + tempStr
        length.append(len(result))
        result = ""
    
    return min(length)

 

압축하는 기준인 cut을 step size로 range에 넣어 주면서 s에 있는 cut size만큼 비교탐색

비교 전에 count = 1, 첫번째 비교 str을 tempStr으로 만들어줌

count = 1으로 설정함으로써 만약에 s을 cut size 만큼 탐색했는데도 pattern이 한번도 일치하지 않을 경우 ""(공백)으로 result에 넣어주기 위함. (count 가 1로 그대로 있다면 1이 아니라 공백으로 바꿔서 result string에 넣어줌)

제일 바깥 for문 마지막에도 count 1 체크를 해줌으로써 마지막 cut size의 비교결과를 넣어줘야 한다.


 

def solution(s):
    LENGTH = len(s)
    cand = [LENGTH]  # 1~len까지 압축했을때 길이 값

    for size in range(1, (LENGTH//2)+1):
        compressed = ""
        # string 갯수 단위로 쪼개기 *
        splited = [s[i:i+size] for i in range(0, LENGTH, size)]
        count = 1
        # print(splited)
        for j in range(1, len(splited)):
            prev, cur = splited[j-1], splited[j]
            if prev == cur:  # 이전 문자와 동일하다면
                count += 1
            else:  # 이전 문자와 다르다면
                compressed += (str(count) + prev) if count > 1 else prev
                count = 1  # 초기화
        
        compressed += (str(count) + splited[-1]) if count > 1 else splited[-1]
        cand.append(len(compressed))

    return min(cand)  # 최솟값 리턴

print(solution("aabbaccc"))

 

728x90

댓글