-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem29.py
More file actions
45 lines (37 loc) · 1.2 KB
/
Copy pathproblem29.py
File metadata and controls
45 lines (37 loc) · 1.2 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
# This problem was asked by Amazon.
# 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. For example,
# the string "AAAABBBCCDAA" would be encoded
# as "4A3B2C1D2A".
# 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.
def encode(string):
count=1
result = ''
for i in range(len(string)):
if i == len(string) - 1:
result += str(count) + string[i]
elif string[i] != string[i+1]:
result += str(count) + string[i]
count = 1
else:
count += 1
return result
def is_digit(c):
return c>='0' and c<='9'
def decode(string):
count = ''
result = ''
for i in range(len(string)):
if(is_digit(string[i])):
count += string[i]
else:
for _ in range(int(count)):
result += string[i]
count = ''
return result
def main():
print(decode(encode('AAAABBBCCDAA')))
if __name__ == '__main__':
main()