Skip to content

Commit eb77e87

Browse files
committed
miguel soln to string compression 1.6
1 parent 666850d commit eb77e87

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Python version 3.7.0
3+
1.6 - String Compression
4+
Implement a method to perform basic string compression using the counts
5+
of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
6+
If the "compressed" string would not become smaller than the original string, your method
7+
should return the original string. You can assume the string has only uppercase and lowercase
8+
letters (a-z).
9+
"""
10+
import unittest
11+
from typing import Callable
12+
13+
14+
def str_compression(s: str) -> str:
15+
"""
16+
String compression will attempt to reduce the size of s by condensing
17+
s using the counts of repeated characters.
18+
Runtime: O(n), asymptotic runtime depends on size of s
19+
Space Complexity: O(n), compressed list
20+
:param s: the string we want to compress
21+
:return: the compressed string or s if the compressed string is not smaller
22+
"""
23+
if len(s) == 0:
24+
return s
25+
compressed = []
26+
prev_char = s[0]
27+
count = 1
28+
for c in s[1:len(s)]:
29+
if c == prev_char:
30+
count += 1
31+
continue
32+
compressed.append(prev_char)
33+
compressed.append(str(count)[0])
34+
prev_char = c
35+
count = 1
36+
# clean up: last character count
37+
compressed.append(prev_char)
38+
compressed.append(str(count)[0])
39+
40+
return ''.join(compressed) if len(compressed) < len(s) else s
41+
42+
43+
class TestStringCompressionFunction(unittest.TestCase):
44+
def _run_tests(self, f: Callable[[str], str]) -> None:
45+
cases = [
46+
('aabcccccaaa', 'a2b1c5a3'),
47+
('abcde', 'abcde'),
48+
('aabbccdd', 'aabbccdd'),
49+
('', ''),
50+
('c', 'c'),
51+
('aaAAccCCCCC', 'a2A2c2C5')
52+
]
53+
for s, expected in cases:
54+
self.assertEqual(f(s), expected, msg=(s, expected))
55+
56+
def test_string_compression(self):
57+
self._run_tests(str_compression)
58+
59+
60+
if __name__ == '__main__':
61+
unittest.main()

0 commit comments

Comments
 (0)