Skip to content

Commit 958bdce

Browse files
committed
✨ [271] Encode and Decode Strings (Premium)
1 parent 0780662 commit 958bdce

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

271/my_solution.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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)

271/solution.js

Whitespace-only changes.

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
- [238. Product of Array Except Self](./238/)
4646
- [242. Valid Anagram](./242/)
4747
- [268. Missing Number](./268/)
48+
- [271. Encode and Decode Strings (Premium)](./271/)
4849
- [371. Sum of Two Integers](./371/)
4950
- [338. Counting Bits](./338/)
5051
- [394. Decode String](./394/)
@@ -83,5 +84,5 @@ Batch create in bash
8384
TODO: Add to TOC!
8485
-->
8586
```ssh
86-
chapter=647 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
87+
chapter=271 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
8788
```

0 commit comments

Comments
 (0)