Encode and Decode Strings
MediumP2Coding
Design a Codec that turns a list of strings into one string and back.
encode(strs)returns a single string that represents the list.decode(s)takes the output ofencodeand returns the original list.
Strings may be empty and may contain any characters, including digits and #, so a plain separator is not safe. To make the output checkable, use this exact format: for every string write its length in decimal, then #, then the string itself, and concatenate the pieces. For example ["hello","world"] encodes to 5#hello5#world, and [""] encodes to 0#. An empty list encodes to the empty string.
Example 1
- Input
- ["Codec","encode"] [[],[["hello","world"]]]
- Output
- [null,"5#hello5#world"]
- Why
- Each string is written as its length, a #, then its characters.
Example 2
- Input
- ["Codec","decode"] [[],["5#hello5#world"]]
- Output
- [null,["hello","world"]]
Example 3
- Input
- ["Codec","encode"] [[],[[""]]]
- Output
- [null,"0#"]
- Why
- An empty string still produces a length prefix.
Constraints
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] may contain any ASCII characters.
- decode is only called with strings produced by encode in the format above.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 16. ⌘Enter runs, ⌘⇧Enter submits.