File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Python/chapter01/1.6 - String Compression Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ 1.6:String Compression: Implement a method to perform basic string compression using
3
+ the counts of repeated characters. For example, the string aabcccccaaa would
4
+ become a2blc5a3. If the "compressed" string would not become smaller than the
5
+ original string, your method should return
6
+ the original string. You can assume the string has only uppercase and lowercase
7
+ letters (a - z).
8
+ """
9
+
10
+
11
+
12
+ def string_compression (str1 ):
13
+ count = 1
14
+ new_str = ""
15
+ for i in range (len (str1 )- 1 ):
16
+ if (str1 [i ] == str1 [i + 1 ]):
17
+ count += 1
18
+ else :
19
+ new_str += str1 [i ] + str (count )
20
+ count = 1
21
+ new_str += str1 [i ] + str (count )
22
+
23
+ if len (new_str ) < len (str1 ):
24
+ return new_str
25
+
26
+ else :
27
+ return str1
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ print (string_compression ('aabcccccaaa' ))
You can’t perform that action at this time.
0 commit comments