forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaewanseoul.ts
More file actions
38 lines (32 loc) · 878 Bytes
/
taewanseoul.ts
File metadata and controls
38 lines (32 loc) · 878 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
/**
* 659 · Encode and Decode Strings
* Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
* Please implement encode and decode
*
* https://leetcode.com/problems/encode-and-decode-strings/description/
* https://www.lintcode.com/problem/659/
*
*/
// O(n) time
// O(1) space
function encode(strs: string[]): string {
let result = "";
for (const str of strs) {
result += `${str.length}#${str}`;
}
return result;
}
// O(n) time
// O(n) space
function decode(str: string) {
const result: string[] = [];
let i = 0;
while (i < str.length) {
let pos = str.indexOf("#", i);
const len = Number(str.slice(i, pos));
const word = str.slice(pos + 1, pos + 1 + len);
result.push(word);
i = pos + 1 + len;
}
return result;
}