Skip to content

Commit 0086bf4

Browse files
author
Chris Cooper
committed
Update 0271-encode-and-decode-strings.py
Shortened the encode function to a one-liner. Refactored decode function to cleanly use index variables i and j.
1 parent 198f27b commit 0086bf4

File tree

1 file changed

+10
-19
lines changed

1 file changed

+10
-19
lines changed
Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,19 @@
11
class Solution:
2-
"""
3-
@param: strs: a list of strings
4-
@return: encodes a list of strings to a single string.
5-
"""
6-
72
def encode(self, strs):
8-
res = ""
9-
for s in strs:
10-
res += str(len(s)) + "#" + s
11-
return res
12-
13-
"""
14-
@param: s: A string
15-
@return: decodes a single string to a list of strings
16-
"""
3+
return ''.join(map(lambda s: str(len(s)) + '#' + s, strs))
174

185
def decode(self, s):
19-
res, i = [], 0
20-
6+
res = []
7+
i = 0
8+
219
while i < len(s):
2210
j = i
23-
while s[j] != "#":
11+
while s[j] != '#':
2412
j += 1
2513
length = int(s[i:j])
26-
res.append(s[j + 1 : j + 1 + length])
27-
i = j + 1 + length
14+
i = j + 1
15+
j = i + length
16+
res.append(s[i:j])
17+
i = j
18+
2819
return res

0 commit comments

Comments
 (0)