forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding_string.py
More file actions
50 lines (37 loc) · 1.06 KB
/
encoding_string.py
File metadata and controls
50 lines (37 loc) · 1.06 KB
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
47
48
49
50
'''
Encoding string
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
You can assume the string to be decoded is valid.
Input: 'AAAABBBCCDAA'
Output: '4A3B2C1D2A'
=========================================
Simple solution, just iterate the string and count.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def encoding(word):
n = len(word)
if n == 0:
return ''
letter = word[0]
length = 1
res = ''
for i in range(1, n):
if word[i] == letter:
length += 1
else:
res += str(length) + letter
letter = word[i]
length = 1
res += str(length) + letter
return res
###########
# Testing #
###########
# Correct result => '4A3B2C1D2A'
print(encoding('AAAABBBCCDAA'))