본문 바로가기
알고리즘/leetcode

443. String Compression

by 1.5볼트 2023. 3. 3.
728x90

https://leetcode.com/problems/string-compression/description/

 

String Compression - LeetCode

Can you solve this real interview question? String Compression - Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: * If the group's leng

leetcode.com

 

 

문자들이 연속적으로 배열에 있으면 연속된 갯수만큼 [문자,연속값,문자,연속값] 처럼 배열을 바꿔 준다 

주의할점은 숫자 한자리는 한칸을 차지한다 만약 a 가 10 번 반복하면 [a,a,a,a,a,a,a,a,a,a] 배열을 [a,10] 이 아니라 [a,1,0]처럼 바꿔야한다  

 

스택을 사용한다

반복문으로 문자를 리스트에 넣으면서 만약 리스트 마지막 문자와 현재 문자가 다르다면 숫자를 배치할차례 마지막부터 숫자를 배치하고 남은 스택을 모두 사용하여 알파벳을 제거하는데 사용한다 

 

class Solution:
    def compress(self, c: List[str]) -> int:
        c+=["ㄱ"]
        n1=0
        t=[]
        n=0
        while len(c)>n1:
            if t and t[-1]!=c[n1]:
                t.pop()
                n=str(n)
                k=1
                m=len(t)-len(n) if len(t)-len(n)>0 else 0
                while t:
                    if n:
                        for i in n[::-1]:
                            c[n1-k]=i
                            k+=1
                            t.pop()
                        n=0
                        continue
                    del c[n1-k]
                    k+=1
                    t.pop()
                n=0
                n1-=m
            else:
                t.append(c[n1])
                n+=1
                n1+=1
        c.pop()
        return len(c)

'알고리즘 > leetcode' 카테고리의 다른 글

101. Symmetric Tree  (0) 2023.03.13
2187. Minimum Time to Complete Trips  (0) 2023.03.07
912. Sort an Array  (0) 2023.03.02
652. Find Duplicate Subtrees (leetcode)  (0) 2023.02.28
540. Single Element in a Sorted Array(Medium)  (0) 2023.02.21

댓글