Question
Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
This is anarrays question.
Idea
- We want some delimiter to separate the strings, and we want to know the length of each string so that we know when the delimiter is actually the delimiter, or just another character.
- prepend each string with the strings length, and a delimiter (4#) and append all the strings together
- To decode, since we know it is guaranteed for the string to start with an int and the delimiter, we can move a pointer to look for the delimiter (#) and then find the strings length by doing s[i:j] since the length could be multiple digits. Now that we know where the string starts and ends, we can slice the string and append to the array, and update our current pointer to the end of the string and repeat. The idea here is since we know the overall string is guaranteed to start with a “5#” sort of format, and we slice the string, we skip over any characters that act like a delimiter in a substring.