forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode_decode.py
55 lines (47 loc) · 1.27 KB
/
encode_decode.py
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
51
52
53
54
55
# Design an algorithm to encode a list of strings to a string.
# The encoded string is then sent over the network and is decoded
# back to the original list of strings.
# Machine 1 (sender) has the function:
# string encode(vector<string> strs) {
# // ... your code
# return encoded_string;
# }
# Machine 2 (receiver) has the function:
# vector<string> decode(string s) {
# //... your code
# return strs;
# }
# So Machine 1 does:
# string encoded_string = encode(strs);
# and Machine 2 does:
# vector<string> strs2 = decode(encoded_string);
# strs2 in Machine 2 should be the same as strs in Machine 1.
# Implement the encode and decode methods.
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
for string in strs.split():
res += str(len(string)) + ":" + string
return res
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
strs.append(s[index+1: index+1+size])
i = index+1+size
return strs
strs = "keon is awesome"
print(strs)
enc = encode(strs)
print(enc)
dec = decode(enc)
print(dec)