forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyer0705.ts
More file actions
47 lines (37 loc) · 994 Bytes
/
hyer0705.ts
File metadata and controls
47 lines (37 loc) · 994 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
42
43
44
45
46
47
class Solution {
private DELIMITER = "*";
/**
* @param strs: a list of strings
* @returns: encodes a list of strings to a single string.
*/
public encode(strs: string[]): string {
let encoded = "";
for (const str of strs) {
encoded += `${str.length}${this.DELIMITER}${str}`;
}
return encoded;
}
/**
* @param str: A string
* @returns: decodes a single string to a list of strings
*/
public decode(str: string): string[] {
const decoded: string[] = [];
let stack: string[] = [];
let pointer = 0;
while (pointer < str.length) {
const char = str[pointer];
if (char === this.DELIMITER) {
let strLength: number = Number(stack.join(""));
stack = [];
const word = str.substring(pointer + 1, pointer + 1 + strLength);
pointer = pointer + 1 + strLength;
decoded.push(word);
} else {
stack.push(char);
pointer++;
}
}
return decoded;
}
}