1
+ '''Question:
2
+ Implement a method to perform basic string compression using the counts of
3
+ repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
4
+
5
+ If the "compressed" string would not become smaller than the original string,
6
+ your method should return the original string.
7
+
8
+ You can assume the string has only uppercase and lowercase letters (a - z).
9
+ '''
10
+
11
+ import unittest
12
+ from test_utils import UnitTestBase
13
+
14
+ # time: O(n)
15
+ # space: O(n)
16
+ def str_comp (s ):
17
+ if s == '' :
18
+ return ''
19
+
20
+ cur , ct , res = s [0 ], 0 , ''
21
+ for c in s :
22
+ if c == cur :
23
+ ct += 1
24
+ else :
25
+ # Note: res = res + cur + str(ct) will be very slow and result in not O(n)
26
+ res += cur + str (ct )
27
+ cur , ct = c , 1
28
+ res += cur + str (ct )
29
+
30
+ # another way to write it: min(s, res, key=len)
31
+ return res if len (res ) < len (s ) else s
32
+
33
+ class TestStrComp (UnitTestBase , unittest .TestCase ):
34
+ def data_provider (self ):
35
+ return [
36
+ ('' , '' ), # 0
37
+ ('a' , 'a' ), # 1
38
+ ('aa' , 'aa' ), # 2
39
+ ('aaa' , 'a3' ), # 3
40
+ ('aaaa' , 'a4' ), # 4
41
+
42
+ ('ab' , 'ab' ), # 11
43
+ ('abb' , 'abb' ), # 12
44
+ ('abbb' , 'abbb' ), # 13
45
+ ('abbbb' , 'a1b4' ), #14
46
+ ('aab' , 'aab' ), # 21
47
+ ('aabb' , 'aabb' ), # 22
48
+ ('aabbb' , 'a2b3' ), # 23
49
+ ('aabbbb' , 'a2b4' ), # 24
50
+ ('aaab' , 'aaab' ), # 31
51
+ ('aaabb' , 'a3b2' ), # 32
52
+ ('aaabbb' , 'a3b3' ), # 33
53
+ ('aaabbbb' , 'a3b4' ), # 34
54
+ ('aaaab' , 'a4b1' ), # 41
55
+ ('aaaabb' , 'a4b2' ), # 42
56
+ ('aaaabbb' , 'a4b3' ), # 43
57
+ ('aaaabbbb' , 'a4b4' ), # 44
58
+
59
+ ('abc' , 'abc' ), # 111
60
+ ('abcc' , 'abcc' ), # 112
61
+ ('abccc' , 'abccc' ), # 113
62
+ ('abbc' , 'abbc' ), # 121
63
+ ('abbcc' , 'abbcc' ), # 122
64
+ ('abbccc' , 'abbccc' ), # 123
65
+ ('abbbc' , 'abbbc' ), # 131
66
+ ('abbbcc' , 'abbbcc' ), # 132
67
+ ('abbbccc' , 'a1b3c3' ), # 133
68
+ ('aabc' , 'aabc' ), # 211
69
+ ('aabcc' , 'aabcc' ), # 212
70
+ ('aabccc' , 'aabccc' ), # 213
71
+ ('aabbc' , 'aabbc' ), # 221
72
+ ('aabbcc' , 'aabbcc' ), # 222
73
+ ('aabbccc' , 'a2b2c3' ), # 223
74
+ ('aabbbc' , 'aabbbc' ), # 231
75
+ ('aabbbcc' , 'a2b3c2' ), # 232
76
+ ('aabbbccc' , 'a2b3c3' ), # 233
77
+ ('aaabc' , 'aaabc' ), # 311
78
+ ('aaabcc' , 'aaabcc' ), # 312
79
+ ('aaabccc' , 'a3b1c3' ), # 313
80
+ ('aaabbc' , 'aaabbc' ), # 321
81
+ ('aaabbcc' , 'a3b2c2' ), # 322
82
+ ('aaabbccc' , 'a3b2c3' ), # 323
83
+ ('aaabbbc' , 'a3b3c1' ), # 331
84
+ ('aaabbbcc' , 'a3b3c2' ), # 332
85
+ ('aaabbbccc' , 'a3b3c3' ), # 333
86
+
87
+ ('aabcccccaaa' , 'a2b1c5a3' ),
88
+ ]
89
+
90
+ def func_provider (self ):
91
+ return [
92
+ str_comp ,
93
+ ]
94
+
95
+ def func_eval (self , func , args ):
96
+ return func (args )
97
+
98
+ if __name__ == '__main__' :
99
+ unittest .main ()
0 commit comments