Skip to main content

#271. Encode and Decode Strings | LeetCode Python Solution

Problem

LeetCode Problem

  1. Encode and Decode Strings

Python Solution

class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""
def encode(self, strs):
encoded_str = ""

# Prefix each string in the list with string length and a pipe symbol
# Concatenate them together into a single string
for s in strs:
encoded_str += str(len(s)) + ("|") + s

return encoded_str

"""
@param: str: A string
@return: dcodes a single string to a list of strings
"""
def decode(self, str):
# Store decoded string in a list
decoded_str_list = []
idx = 0
while idx < len(str):
# Initialize ptr to idx.
ptr = idx

# Advance ptr to the pipe separator |
while str[ptr] != '|':
ptr += 1

# Find out how many chars we need to extract
num_of_chars = int(str[idx: ptr])

# Extract decoded string and append it to the list
decoded = str[ptr+1: ptr+1+num_of_chars]
decoded_str_list.append(decoded)

# Advance ptr to the next section to decode
idx = ptr+1+num_of_chars
print(idx)

return decoded_str_list