코딩테스트/Python
[LeetCode] 443. String Compression
swwho
2025. 3. 26. 00:34
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
- 우선, 주어진 chars를 그대로 결과에 반영하기 위해 clear()를 해주어야 한다.
- 문자열 압축에서, 두 자리의 개수는 list()를 통해 split 하여 저장한다.