Instructions
Write a class Codec with two methods:
encode(strs)gets a list of strings and returns one string.decode(s)gets a string made byencodeand returns the original list: the same strings, in the same order.
The strings can contain any printable character, including the characters you might want to use as a separator (#, ,, |, digits, quotes, spaces). A string can be empty, and the list itself can be empty. [], [""] and ["", ""] are three different lists, and each must come back exactly as it was.
How the judge checks your code
For each test the judge:
- creates one
Codecobject and callsencode(strs). The result must be a string; anything else fails the test; - creates a second, new
Codecobject and callsdecodeon that string; - compares the list that
decodereturns withstrs.
Because decode runs on a different object, saving the list inside the object during encode does not work. Everything must be inside the string.
A built-in serializer such as JSON.stringify or json.dumps would pass the tests, but the goal of this problem is to design the format yourself.
How the input is shown
The input is the list strs itself, for example ["ab", "", "c#d"]. The expected output is the same list.
Hint: put the length of each string in front of it, followed by a marker, for example "3#abc". When you decode, read the number up to the marker, then take exactly that many characters. The characters inside a string are never read as a number or a marker, so they can be anything.
Examples
Example 1
- Input:
- ["red","a,b",""]
- Output:
- ["red","a,b",""]
The second string contains a comma and the third is empty. With a length prefix the string could be "3#red3#a,b0#", which decodes back to the same three strings. Joining with "," would give "red,a,b," and lose the boundaries.
Example 2
- Input:
- ["12#x","#","\"q\""]
- Output:
- ["12#x","#","\"q\""]
The strings themselves look like length prefixes and contain the "#" marker and quotes. A decoder that reads exactly the stated number of characters never looks inside them, so they cause no trouble.
Example 3
- Input:
- []
- Output:
- []
The empty list must decode to the empty list, not to [""]. encode still has to return a string (an empty string is fine).
Constraints
0 <= strs.length <= 100 <= strs[i].length <= 30strs[i]contains only printable ASCII characters (space to~, codes 32 to 126).
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- ["red","a,b",""]
- Expected:
- ["red","a,b",""]
- Input:
- ["12#x","#","\"q\""]
- Expected:
- ["12#x","#","\"q\""]
- Input:
- []
- Expected:
- []
Run checks your code against the 3 examples. Submit checks it against all 123 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.