DEV Community

Stylus07
Stylus07

Posted on

2 1

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️