Skip to content

Commit 9bc1fdc

Browse files
committed
feat: 271. Encode and Decode Strings
1 parent 355a40c commit 9bc1fdc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* The most simple way
3+
*/
4+
function encode(strs: string[]): string {
5+
return strs.join('🏖️');
6+
};
7+
function decode(s: string): string[] {
8+
return s.split('🏖️');
9+
};
10+
11+
// T.C: O(n)
12+
// S.C: O(n)
13+
function encode(strs: string[]): string {
14+
return strs.map((s) => s.length + '#' + s).join('');
15+
}
16+
17+
// T.C: O(n)
18+
// S.C: O(n)
19+
function decode(s: string): string[] {
20+
const res: string[] = [];
21+
let curIdx = 0;
22+
while (curIdx < s.length) {
23+
const sepIdx = s.indexOf('#', curIdx);
24+
const len = parseInt(s.slice(curIdx, sepIdx), 10);
25+
res.push(s.slice(sepIdx + 1, sepIdx + 1 + len));
26+
curIdx = sepIdx + 1 + len;
27+
}
28+
return res;
29+
}

0 commit comments

Comments
 (0)