Design an algorithm to encode a list of strings to a single string and decode it back. The encoded string is transmitted over a network — it must be decodable even when individual strings contain special characters like #, ,, or any other byte.
["hello","world"]"5#hello5#world"["hello","world"] ✓["we","say",":","yes"]"2#we3#say1#:3#yes""len#word" to bufferi = 0; loop while i < enc.lengthj = indexOf('#', i); parse len = enc[i..j]enc[j+1 .. j+1+len]; advance i = j+1+lenA simple delimiter (comma, pipe) fails if strings contain that delimiter. Length-prefix encoding is unambiguous: parse the integer before #, then read exactly that many characters — no special character inside the word can interfere. Even strings containing # (e.g. "5#hello") decode correctly.
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.
Length prefixes make any content safe. Read the length first, then read exactly that many characters.
Run the animation above on your own input, or watch the 1:32 video explanation of Encode and Decode Strings with a dry run and Java code.