Skip to content

Commit 88c4d77

Browse files
committed
encode and decode strings solution
1 parent 635eff6 commit 88c4d77

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
private DELIMITER = "*";
3+
4+
/**
5+
* @param strs: a list of strings
6+
* @returns: encodes a list of strings to a single string.
7+
*/
8+
public encode(strs: string[]): string {
9+
let encoded = "";
10+
11+
for (const str of strs) {
12+
encoded += `${str.length}${this.DELIMITER}${str}`;
13+
}
14+
15+
return encoded;
16+
}
17+
18+
/**
19+
* @param str: A string
20+
* @returns: decodes a single string to a list of strings
21+
*/
22+
public decode(str: string): string[] {
23+
const decoded: string[] = [];
24+
25+
let stack: string[] = [];
26+
let pointer = 0;
27+
28+
while (pointer < str.length) {
29+
const char = str[pointer];
30+
31+
if (char === this.DELIMITER) {
32+
let strLength: number = Number(stack.join(""));
33+
stack = [];
34+
35+
const word = str.substring(pointer + 1, pointer + 1 + strLength);
36+
pointer = pointer + 1 + strLength;
37+
38+
decoded.push(word);
39+
} else {
40+
stack.push(char);
41+
pointer++;
42+
}
43+
}
44+
45+
return decoded;
46+
}
47+
}

0 commit comments

Comments
 (0)