762. Encode a list of strings into one string and decode it back
Sending a batch of prompts over a channel that only carries one string, or writing them to one file field, needs a reversible encoding. Picking a separator character fails as soon as some string contains that character.
Write two functions. encode(strings) takes a list of strings and returns a single string. decode(s) takes a string produced by encode and returns the original list exactly. Strings may contain any characters, including digits, '#', ':', commas, newlines and nothing at all (the empty string). Do not use json, pickle, repr or eval.
def encode(strings)Example 1
Input: decode(encode(['hello', 'wor:ld']))
Output: ['hello', 'wor:ld']
Example 2
Input: decode(encode([]))
Output: [] and decode(encode([''])) returns ['']
Example 3
Input: decode(encode(['3:abc', '', '12', '\n', '#,#', ':::']))
Output: ['3:abc', '', '12', '\n', '#,#', ':::']
Constraints
- At most 10,000 strings.
- Total length at most 1,000,000 characters.
Hint 1
Prefix each string with its length.
Hint 2
Use a delimiter only to end the length digits.
Hint 3
Slice by length when decoding instead of searching for the next delimiter.
Common mistakes
- Joining with a separator such as ',' that can appear inside a string.
- Losing empty strings or confusing [] with [''].
- Searching for the delimiter inside the content while decoding.
Understand the idea
Framing is the problem of marking where one message ends and the next begins. Separators need escaping; length prefixes do not. The same idea appears in network protocols, record files and tokenizer vocab files.