[LeetCode] 443. String Compression

2025. 3. 26. 00:34·코딩테스트/Python
728x90
반응형

🔗 Problem Link

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


❔Thinking

  • 주어진 문자 배열을 압축한다 (ex - ['a','a'] -> ['a','2'])
  • 주어진 문자 배열에 압축한 결과를 저장한다.

💻Solution

def compress(self, chars: List[str]) -> int:
    compressed = []
    n = len(chars)
    cnt = 0
    for i in range(1, len(chars)):
        if chars[i] == chars[i-1]:
            cnt += 1
        else:
            cnt += 1
            compressed.append(chars[i-1])
            if cnt>=2: compressed.extend(list(str(cnt)))
            cnt = 0
    if cnt == 0:
        compressed.append(chars[-1])
    else:
        compressed.append(chars[i-1])
        cnt += 1
        if cnt>=2: 
            compressed.extend(list(str(cnt)))
            print(list(str(cnt)))

    chars.clear()
    chars.extend(compressed)
    return len(chars)

🗝️keypoint

  1. 우선, 주어진 chars를 그대로 결과에 반영하기 위해 clear()를 해주어야 한다.
  2. 문자열 압축에서, 두 자리의 개수는 list()를 통해 split 하여 저장한다.
저작자표시 (새창열림)

'코딩테스트 > Python' 카테고리의 다른 글

[LeetCode] 283. Move Zeroes  (0) 2025.04.07
[Programmers] Level 2. 아날로그 시계  (0) 2025.03.26
[LeetCode] 238. Product of Array Except Self  (0) 2025.03.24
[LeetCode] 345. Reverse Vowels of a String  (0) 2025.03.19
[LeetCode] 605. Can Place Flowers  (0) 2025.03.18
'코딩테스트/Python' 카테고리의 다른 글
  • [LeetCode] 283. Move Zeroes
  • [Programmers] Level 2. 아날로그 시계
  • [LeetCode] 238. Product of Array Except Self
  • [LeetCode] 345. Reverse Vowels of a String
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (189)
      • ML_DL (40)
        • MUJAKJUNG (무작정 시리즈) (19)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[LeetCode] 443. String Compression
상단으로

티스토리툴바