Skip to content
BytePatterns

Pack a Word List Into One String

EasyStrings#length-prefix#string-parsing~20m

Problem

Write pack(words), which turns a list of strings into one string, and unpack(text), which turns that string back into the original list. Each word is written as its length in decimal, then a #, then the word itself. Words can be empty and can contain any character, including digits and #, so unpack must never search for a separator inside a word.

Examples

Input:  words = ["hi", "#1"]
Output: pack   -> "2#hi2##1"
        unpack -> ["hi", "#1"]
Why:    after reading "2#", the next two characters are taken whole, "#" or not
Input:  words = ["", "a"]
Output: pack   -> "0#1#a"
Why:    an empty word still gets its length, so it survives the round trip
Input:  words = []
Output: pack   -> ""
        unpack -> []
Why:    edge case, nothing to write and nothing to read

Hints

0 / 3

Stuck on the idea rather than the code? Encode and Decode Strings covers it.