April 20, 2022 02:54 am GMT
Original Link: https://dev.to/styluso7/encode-and-decode-strings-3i96
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To