Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
Please implement encode and decode
Example 1:
Input: ["neet","code","love","you"]
Output:["neet","code","love","you"] Example 2:
Input: ["we","say",":","yes"]
Output: ["we","say",":","yes"]
In [11]:
def encode(strs):
res = ''
for s in strs:
res+=str(len(s))+":"+s
return res
print(encode(["4","","love","you"]))
def decode(s):
res=[]
i=0
while i<len(s):
# Step 1: Read the number before the colon
strnum=''
while s[i]!=":":
strnum += s[i]
i+=1
num=int(strnum)
# Step 2: Extract the string after the colon
res.append(s[i+1:i+num+1])
# Step 3: Move the pointer to the next part
i=i+num+1
return res
print(decode('1:40:4:love3:you'))
1:40:4:love3:you ['4', '', 'love', 'you']
In [12]:
a='abcd'
a[0:2]
Out[12]:
'ab'