DEV Community

Stylus07
Stylus07

Posted on

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) {
        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;
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(n)

Top comments (0)