This content originally appeared on DEV Community and was authored by Stylus07
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
var encode = function (strs) {
let res = '';
for (let char of strs) {
res += (char.length).toString() + `#` + char;
}
return res;
}
var decode = function (s) {
let res = [];
for (let i = 0; i < s.length; i++) {
let j = i;
while (s[j] != '#') {
j++;
}
let wordLength = parseInt(s.substring(i, j));
res.push(s.substring(j + 1, j + 1 + wordLength));
i = j + wordLength;
}
return res;
}
Time Complexity : O(n)
This content originally appeared on DEV Community and was authored by Stylus07
Stylus07 | Sciencx (2022-04-20T02:54:56+00:00) Encode and Decode Strings. Retrieved from https://www.scien.cx/2022/04/20/encode-and-decode-strings/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.