[Leetcode]443. String Compression(x)
2024. 7. 28. 09:43ㆍAlgorithm
1. problem :
2. solution 1 :
class Solution:
def compress(self, chars: List[str]) -> int:
if not chars:
return 0
write_index = 0
read_index = 0
n = len(chars)
while read_index < n:
char = chars[read_index]
count = 0
# Count the number of occurrences of the current character
while read_index < n and chars[read_index] == char:
read_index += 1
count += 1
# Write the character
chars[write_index] = char
write_index += 1
# Write the count if it's more than 1
if count > 1:
for digit in str(count):
chars[write_index] = digit
write_index += 1
return write_index
내가 문제 이해를 못 해서, 못 풀었다. 따라서, gpt 4o가 짜준 코드를 기반으로 해석한다.
첫 번째로, read_index와 write_index를 둔다. read는 리스트를 순차적으로 훑어보는 역할이고, write는 기존에 있던 리스트에 쓰는 역할이다.
두 번째로, while read < n: 을 한 다음, 초기값으로 char = chars [read], count = 0을 설정해 준다.
세 번째로, while read < n and chars [read] == char 조건에서만 루프를 실행한다. 예를 들어, char = "a"이고 , "a"가 계속 나오다가, "b"가 나오면, loop가 종료된다. 이때, read는 "b"를 가리키게 된다. 이제 이것을 토대로, wrtie를 이용해서 , 기존에 있던 input_list에 새겨 넣자. 그다음, "b"부터 다시 시작한다. 이때, count > 1 때만, count를 써야 하니 조건도 추가해 줬다.
네 번째로, str(count)는 "123"일 때, digit 은 순차적으로 "1" , "2" , "3"을 뱉는다. 이때, write를 이용해서 적어주고 , +=1 시켜준다.
마지막으로, loop가 끝나면 write_index를 반환한다.
'Algorithm' 카테고리의 다른 글
[BOJ]10808(O) (0) | 2024.07.28 |
---|---|
[Leetcode]283. Move Zeroes(n^2말고 다른풀이로 풀어볼것) (0) | 2024.07.28 |
[BOJ]2231번 분해합 (0) | 2024.07.27 |
[Leetcode]334. Increasing Triplet Subsequence(x) (0) | 2024.07.27 |
[Leetcode]238. Product of Array Except Self (0) | 2024.07.27 |