forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsukyoungshin.ts
More file actions
41 lines (33 loc) · 856 Bytes
/
sukyoungshin.ts
File metadata and controls
41 lines (33 loc) · 856 Bytes
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
29
30
31
32
33
34
35
36
37
38
39
40
41
// https://neetcode.io/problems/string-encode-and-decode
class Solution {
/**
* @param {string[]} strs
* @returns {string}
*/
encode(strs) {
let encodedStrings: string[] = [];
for (const word of strs) {
const length = word.length;
encodedStrings.push(`${length}#${word}`);
}
return encodedStrings.join("");
}
/**
* @param {string} str
* @returns {string[]}
*/
decode(str) {
const decodedStrings: string[] = [];
let position = 0;
while (position < str.length) {
const hashIndex = str.indexOf("#", position);
const length = Number(str.slice(position, hashIndex));
const start = hashIndex + 1;
const end = start + length;
const word = str.slice(start, end);
decodedStrings.push(word);
position = end;
}
return decodedStrings;
}
};