-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path0443-string-compression.py
More file actions
46 lines (33 loc) · 972 Bytes
/
0443-string-compression.py
File metadata and controls
46 lines (33 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 443. String Compression
# https://leetcode.com/problems/string-compression
class Solution:
def compress(self, chars: list[str]) -> int:
n = len(chars)
if n == 1:
return 1
i = 0
j = 0
count = 0
while i < n:
count += 1
if i == n - 1 or chars[i + 1] != chars[i]:
chars[j] = chars[i]
j += 1
if count > 1:
for char in str(count):
chars[j] = char
j += 1
count = 0
i += 1
return j
# ********************#
# TEST #
# ********************#
import unittest
class TestStringMethods(unittest.TestCase):
def test_addBinary(self):
self.assertEqual(Solution.compress(self, ["a", "a", "b", "b", "c", "c", "c"]), 6)
self.assertEqual(Solution.compress(self, ["a"]), 1)
self.assertEqual(Solution.compress(self, ["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]), 4)
if __name__ == '__main__':
unittest.main()