Encode and Decode
medium
String
Challenge
Design an algorithm to encode a list of strings to a single string. The encoded string is then sent over the network and is decoded back to the original list of strings.
<Code />
// Put a colon between the length and the string, then join them together.
function encode(strs) {
return strs.map((str) => `${str.length}:${str}`).join("");
}
// Split the string by the colon, then extract the length and the string.
function decode(str) {
let res = [];
let i = 0;
while (i < str.length) {
let colon = str.indexOf(":", i);
let len = Number(str.slice(i, colon));
let item = str.slice(colon + 1, colon + 1 + len);
res.push(item);
i = colon + 1 + len;
}
return res;
}
Thoughts
This problem is fun because it really doesn't force you to rely on computer science knowledge. You could give this problem to someone who'd never seen a computer before and they could give it a shot.
At first it seems tricky because you realize that any delimiter you choose could be in the string. But, because you are guaranteed to see your delimiter first, and you can set the length, then you can ignore the delimiter if it appears within the string.