Design an encode function that turns a list of strings into one string. And a decode function that turns that string back into the exact same list. The strings can contain any character, including the one you might want to use as a separator.
DSA Animator › DSA Revision › Strings › Encode and Decode Strings
Remember: length prefixes make any content safe. Read the length first, then read exactly that many characters. The video solves Encode and Decode Strings (LeetCode 271, Medium) with the Length Prefix pattern from the Strings topic, and you can replay every step in the interactive Encode and Decode Strings animation.
Design an encode function that turns a list of strings into one string. And a decode function that turns that string back into the exact same list. The strings can contain any character, including the one you might want to use as a separator.
For the list h i, and a hash b, the encoded string is 2 hash h i, 3 hash a hash b. Decoding it gives back h i, and a hash b.
Joining with a separator, like a comma, breaks as soon as a word contains a comma. Escaping special characters works, but it is fiddly and easy to get wrong.
Put the length of each word in front of it, followed by a hash. To decode, read digits up to the hash, which gives the length. Then take exactly that many characters, no matter what they are.
Encode h i as 2, hash, h i. Encode a hash b as 3, hash, a hash b. Decoding starts at 0: the digits before the first hash say 2, so read h i. Next, the digits say 3, so read the next 3 characters, a hash b, even though one of them is a hash. The list comes back exactly as it was.
In code, encode appends the length, a hash, and the word, for every word. Decode finds the next hash from the current index, and parses the length before it. It takes that many characters after the hash, and jumps past them. Both directions are O of total length in time and space.
Remember: length prefixes make any content safe. Read the length first, then read exactly that many characters.