Skip to content

Commit

Permalink
Update 0271-encode-and-decode-strings.py
Browse files Browse the repository at this point in the history
Shortened the encode function to a one-liner.
Refactored decode function to cleanly use index variables i and j.
  • Loading branch information
coopers committed Sep 1, 2023
1 parent 198f27b commit 0086bf4
Showing 1 changed file with 10 additions and 19 deletions.
29 changes: 10 additions & 19 deletions python/0271-encode-and-decode-strings.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""

def encode(self, strs):
res = ""
for s in strs:
res += str(len(s)) + "#" + s
return res

"""
@param: s: A string
@return: decodes a single string to a list of strings
"""
return ''.join(map(lambda s: str(len(s)) + '#' + s, strs))

def decode(self, s):
res, i = [], 0

res = []
i = 0

while i < len(s):
j = i
while s[j] != "#":
while s[j] != '#':
j += 1
length = int(s[i:j])
res.append(s[j + 1 : j + 1 + length])
i = j + 1 + length
i = j + 1
j = i + length
res.append(s[i:j])
i = j

return res

0 comments on commit 0086bf4

Please sign in to comment.