Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 20, 2022 02:54 am GMT

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;}

Time Complexity : O(n)


Original Link: https://dev.to/styluso7/encode-and-decode-strings-3i96

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To