-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path271-encode-and-decode-strings.ts
More file actions
61 lines (52 loc) · 1.22 KB
/
Copy path271-encode-and-decode-strings.ts
File metadata and controls
61 lines (52 loc) · 1.22 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Encode with lsit of word sizes, #, then all strings together
* Decode by reconstructing sizes array, then loop through all words
*/
class Solution {
/**
* @param {string[]} strs
* @returns {string}
*/
encode(strs: string[]): string {
if (strs.length === 0) return '';
let sizes = [];
let res = '';
for (let s of strs) {
sizes.push(s.length);
}
for (let sz of sizes) {
res += sz + ',';
}
res += "#";
for (let s of strs) {
res += s;
}
return res;
}
/**
* @param {string} str
* @returns {string[]}
*/
decode(str: string): string[] {
if (str.length === 0) return [];
let sizes = [],
res = [],
i = 0;
while (str[i] !== "#") {
let cur = '';
// get length of next word
while (str[i] !== ',') {
cur += str[i];
i++;
}
sizes.push(parseInt(cur));
i++;
}
i++; // skip #
for (let sz of sizes) {
res.push(str.slice(i, sz + i));
i += sz;
}
return res;
}
}