-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path271 Encode and Decode Strings.py
92 lines (72 loc) · 2.08 KB
/
271 Encode and Decode Strings.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Premium Question
Author: Rajeev Ranjan
"""
class Codec(object):
def encode(self, strs):
"""
Encodes a list of strings to a single string.
Algorithm: Length info
:type strs: List[str]
:rtype: str
"""
strs = map(lambda x: str(len(x))+"/"+x, strs)
return reduce(lambda x, y: x+y, strs, "") # i.e. "".join(strs)
def decode(self, s):
"""
Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
j = s.index("/", i)
l = int(s[i:j])
strs.append(s[j+1:j+1+l])
i = j+1+l
return strs
class CodecMethod2(object):
def encode(self, strs):
"""
Encodes a list of strings to a single string.
Algorithm: Escape
:type strs: List[str]
:rtype: str
"""
strs = map(lambda x: x.replace("\n", "\n\n")+"_\n_", strs)
return reduce(lambda x, y: x+y, strs, "")
def decode(self, s):
"""
Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = s.split("_\n_")
strs = strs[:-1] # clear the trailing delimiter
return map(lambda x: x.replace("\n\n", "\n"), strs)
class CodecError(object):
def encode(self, strs):
"""
Encodes a list of strings to a single string.
This algorithm contains bugs if \\x00 exits in the original string
:type strs: List[str]
:rtype: str
"""
strs = map(lambda x: x.replace("\x00", "\\x00"), strs)
ret = ""
for s in strs:
ret += s+"\x00"
return ret
def decode(self, s):
"""
Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
if "\x00" not in s:
return []
s = s[:-1] # traiing \x00
strs = s.split("\x00")
strs = map(lambda x: x.replace("\\x00", "\x00"), strs)
return strs