Encode and Decode Strings
MediumArrays & Hashing
Design a way to pack a list of strings into one string and unpack it again. Implement two functions:
encode(strs)takes a list of strings and returns a single string.decode(data)takes a string produced by yourencodeand returns the original list.
You choose the format. The only requirement is that decode(encode(strs)) gives back a list equal to strs for every valid input: the same strings, in the same order, with the same count. Strings may be empty and may contain any ASCII character, including ones you might be tempted to use as separators such as #, ,, digits, spaces and newlines. Do not lean on a built-in serializer (json, pickle, repr/eval); the point is to design the format yourself.
Each test calls your encode on a list, passes the result to your decode, and compares what comes back with the original list. The examples below show that round-trip result.
Example 1
- Input:
- strs = ["code","ground",""]
- Output:
- ["code","ground",""]
- Explanation
- One format that works: write each string's length, a
#, then the string itself, giving4#code6#ground0#. The trailing0#records the empty string, so decoding recovers all three entries.
Example 2
- Input:
- strs = ["a,b","#","12#x"]
- Output:
- ["a,b","#","12#x"]
- Explanation
- Joining on
,or#would split these strings in the wrong places. With a length prefix (3#a,b1##4#12#x) the decoder reads a length, then takes exactly that many characters, so separator-like content is harmless.
Example 3
- Input:
- strs = []
- Output:
- []
- Explanation
- The empty list must come back as
[], which is different from[""](a list holding one empty string).
Constraints
0 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]may contain any of the 256 ASCII characters (codes 0 to 255)