Encode and Decode Strings
Design an algorithm to encode a list of strings into a single string and decode it back.
Implement encode(strs), which takes a list of strings and returns one string, and decode(s), which takes that string and returns the original list. For every valid input, decode(encode(strs)) must equal strs exactly (same order, same count, empty strings preserved).
Input: a list of strings (the example shows it comma-separated for display only). Output: the decoded strings, one per line.
Example
hello,world
hello world
- Input: a list of strings,
helloandworld(shown comma-separated only for display), each 5 characters long.encodemust turn the whole list into one string;decodemust turn that string back into exactly the original list. - The requirement: decoding must undo encoding, for every list , including the empty list, empty strings, and strings that contain commas or any other character.
- Why plain joining fails: the lists [
hello,world], [hellow,orld] and [helloworld] all glue into the same 10 characters. If two different lists produce the same encoded string, no decoder can tell which one it came from, so the encoding must record where each string ends without relying on any character being absent from the data. - Output: the recovered list has 2 entries, printed one per line:
hellothenworld. - Notice that a comma delimiter would break on a list holding the string "a,b" and an empty string: it must come back as 2 strings, not 3.
Constraints
- 0 <= len(strs) <= 200
- 0 <= len(strs[i]) <= 200
- strs[i] may contain any character including commas