Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode.
Note:
Because the string may contain any of the 256 legal ASCII characters, your algorithm must be able to handle any character that may appear
Do not rely on any libraries, the purpose of this problem is to implement the “encode” and “decode” algorithms on your own
There are multiple ways we can encode string. For eg. using special char like # to separate the strings while encoding. But the problem is what if the special char is part of string. Then it will be a problem.
What we can do is use special char like # but also append or prepend number of chars of string we have. For eg. we -> we#2.
publicclassCodec {
// Encodes a list of strings to a single string.public String encode(List<String> strs) {
StringBuilder sb =new StringBuilder();
for (String str: strs) {
sb.append(str.length()).append('/').append(str);
}
return sb.toString();
}
// Decodes a single string to a list of strings.public List<String>decode(String s) {
List<String> ans =new ArrayList<>();
int i = 0;
while (i < s.length()) {
int slash = s.indexOf('/', i);
int size = Integer.valueOf(s.substring(i, slash));
ans.add(s.substring(slash + 1, slash + size + 1));
i = slash + size + 1;
}
}
}
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""defencode(self, strs):
res =''for s in strs:
encoded = str(len(s)) +'/'+ s
res += encoded
return res """
@param: str: A string
@return: dcodes a single string to a list of strings
"""defdecode(self, str):
res, i = [], 0while i < len(str):
# For example, 12/abc e = i
while e < len(str) and str[e] !='/':
e +=1 size = int(str[i:e])
word = str[e +1, e +1+ size]
i = e +1+ size
res.append(word)
return res