Skip to content

Commit 12ec55e

Browse files
committed
encode-and-encode-strings
1 parent 0e438e4 commit 12ec55e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 659 · Encode and Decode Strings
3+
* 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.
4+
* Please implement encode and decode
5+
*
6+
* https://leetcode.com/problems/encode-and-decode-strings/description/
7+
* https://www.lintcode.com/problem/659/
8+
*
9+
*/
10+
11+
// O(n) time
12+
// O(1) space
13+
function encode(strs: string[]): string {
14+
let result = "";
15+
16+
for (const str of strs) {
17+
result += `${str.length}#${str}`;
18+
}
19+
20+
return result;
21+
}
22+
23+
// O(n) time
24+
// O(n) space
25+
function decode(str: string) {
26+
const result: string[] = [];
27+
28+
let i = 0;
29+
while (i < str.length) {
30+
let pos = str.indexOf("#", i);
31+
const len = Number(str.slice(i, pos));
32+
const word = str.slice(pos + 1, pos + 1 + len);
33+
result.push(word);
34+
i = pos + 1 + len;
35+
}
36+
37+
return result;
38+
}

0 commit comments

Comments
 (0)