|
| 1 | +// 271. Encode and Decode Strings (Premium) |
| 2 | + |
| 3 | +// [“I”,“love”,“google”,“haha”,“hahaha”] |
| 4 | +const encode = (strList) => { |
| 5 | + let positionStr = "", len = 0, str = strList.join(""); |
| 6 | + |
| 7 | + // “len,1-1,5-5,11-,..._Ilovegooglehahahahaha” |
| 8 | + while (0 < strList.length) { |
| 9 | + let curr = strList.shift(); |
| 10 | + // console.log(`curr:${curr} - ${len},${curr.length}`) |
| 11 | + positionStr += `${len},${curr.length}-`; |
| 12 | + len += curr.length; |
| 13 | + } |
| 14 | + |
| 15 | + return `${positionStr}_${str}`; |
| 16 | +} |
| 17 | + |
| 18 | +// split - pop -> string for slice( |
| 19 | +const decode = (str) => { |
| 20 | + let splitStr = str.split("_"); // …., “Ilove…” |
| 21 | + // handle edge case |
| 22 | + if (2 > splitStr.length) return 404; |
| 23 | + |
| 24 | + // “1,2-3,4- |
| 25 | + let positionStr = splitStr[0], originalJoinedStr = splitStr[1]; |
| 26 | + positionStr = positionStr.split("-"); // [“1,2”, “3,4”] |
| 27 | + positionStr.pop(); |
| 28 | + let decodedStrList = []; |
| 29 | + |
| 30 | + |
| 31 | + while (0 < positionStr.length) { |
| 32 | + let curr = positionStr.shift(); |
| 33 | + curr = curr.split(","); // [1, 2] |
| 34 | + decodedStrList.push(originalJoinedStr.slice(parseInt(curr[0]), parseInt(curr[0]) + parseInt(curr[1]))); |
| 35 | + } |
| 36 | + |
| 37 | + return decodedStrList; |
| 38 | +} |
| 39 | + |
| 40 | +let x = encode(["I", "love", "google", "LOL", "Lmao"]); |
| 41 | +console.log("x") |
| 42 | +console.log(x) |
| 43 | + |
| 44 | +let y = decode(x); |
| 45 | +console.log("y") |
| 46 | +console.log(y) |
0 commit comments