Encode and Decode Strings
Problem: Encode and Decode Strings
We can add length of string into encoded strings so that we can decode successfully. To tell the length from characters, we can use a special symbol.
Code in Python:
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ""
for string in strs:
res += str(len(string))+"/"+string
return res
def decode(self, s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
res = []
i = 0
while i < len(s):
j = s.find("/", i)
i = j+int(s[i:j])+1
res.append(s[j+1:i])
return res