Skip to content

Commit db5924b

Browse files
committed
add : #238 Encode and Decode Strings
1 parent 8787193 commit db5924b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// https://neetcode.io/problems/string-encode-and-decode
2+
3+
class Solution {
4+
/**
5+
* @param {string[]} strs
6+
* @returns {string}
7+
*/
8+
encode(strs) {
9+
let encodedStrings: string[] = [];
10+
11+
for (const word of strs) {
12+
const length = word.length;
13+
encodedStrings.push(`${length}#${word}`);
14+
}
15+
16+
return encodedStrings.join("");
17+
}
18+
19+
/**
20+
* @param {string} str
21+
* @returns {string[]}
22+
*/
23+
decode(str) {
24+
const decodedStrings: string[] = [];
25+
let position = 0;
26+
27+
while (position < str.length) {
28+
const hashIndex = str.indexOf("#", position);
29+
const length = Number(str.slice(position, hashIndex));
30+
31+
const start = hashIndex + 1;
32+
const end = start + length;
33+
const word = str.slice(start, end);
34+
decodedStrings.push(word);
35+
36+
position = end;
37+
}
38+
39+
return decodedStrings;
40+
}
41+
};

0 commit comments

Comments
 (0)