Encode and Decode Strings

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) {


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Encode and Decode Strings." Stylus07 | Sciencx - Wednesday April 20, 2022, https://www.scien.cx/2022/04/20/encode-and-decode-strings/
HARVARD
Stylus07 | Sciencx Wednesday April 20, 2022 » Encode and Decode Strings., viewed ,<https://www.scien.cx/2022/04/20/encode-and-decode-strings/>
VANCOUVER
Stylus07 | Sciencx - » Encode and Decode Strings. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/20/encode-and-decode-strings/
CHICAGO
" » Encode and Decode Strings." Stylus07 | Sciencx - Accessed . https://www.scien.cx/2022/04/20/encode-and-decode-strings/
IEEE
" » Encode and Decode Strings." Stylus07 | Sciencx [Online]. Available: https://www.scien.cx/2022/04/20/encode-and-decode-strings/. [Accessed: ]
rf:citation
» Encode and Decode Strings | Stylus07 | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.