Encode/Decode Strings

July 30th, 2022

#cs fundamentals, #array

Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Key Observations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/** * Encodes a list of strings to a single string. * * @param {string[]} strs * @return {string} */ const hashFn = (char) => { if (char === '') return ''; return `${char.charCodeAt()}`; }; const unhashFn = (num) => { if (num === '') return ''; return String.fromCharCode(parseInt(num, 10)); }; var encode = function (strs) { const rtrn = strs.map((str) => str.split('').map(hashFn).join(' ')).join(','); // delimiter for words is . return rtrn; }; /** * Decodes a single string to a list of strings. * * @param {string} s * @return {string[]} */ var decode = function (s) { const rtrn = s.split(',').map((str) => { const rtrn = str.split(' ').map(unhashFn).join(''); return rtrn; }); console.log('decode', rtrn); return rtrn; }; /** * Your functions will be called as such: * decode(encode(strs)); */