-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-encode-and-decode.ts
71 lines (59 loc) · 1.33 KB
/
string-encode-and-decode.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Design an algorithm to encode a list of strings to a single string.
The encoded string is then decoded back to the original list of strings.
Constraints:
0 <= strs.length < 100
0 <= strs[i].length < 200
strs[i] contains only UTF-8 characters.
*/
const EXAMPLES = [
{
input: ['neet', 'code', 'love', 'you'],
output: ['neet', 'code', 'love', 'you'],
},
{
input: ['we', 'say', ':', 'yes'],
output: ['we', 'say', ':', 'yes'],
},
];
const DELIMITER = '#';
/**
* Encode
* Time O(n) | Space O(n)
*/
function encode(strings: string[]): string {
return strings
.map((string) => `${string.length}${DELIMITER}${string}`)
.join('');
}
/**
* Decode
* Time O(n) | Space O(n)
*/
function decode(s: string): string[] {
let res: string[] = [];
let i = 0;
while (i < s.length) {
let j = i;
while (s[j] !== '#') {
j += 1;
}
let length = parseInt(s.slice(i, j));
i = j + 1;
j = i + length;
res.push(s.slice(i, j));
i = j;
}
return res;
}
function encodeAndDecodeString(strings: string[]): string[] {
return decode(encode(strings));
}
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('String Encode & Decode', () => {
EXAMPLES.forEach((example) => {
expect(encodeAndDecodeString(example.input)).toEqual(example.output);
});
});
}