-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443-string-compression.js
More file actions
47 lines (38 loc) · 908 Bytes
/
443-string-compression.js
File metadata and controls
47 lines (38 loc) · 908 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
/**
* start: 0820 17:20
* end: 0820 18:00
*
* @param {string[]} chars
* @return {number}
*/
function compress(chars) {
/** @type {{ char: string; count: number; } | null} */
let cursor = null;
chars.push(null);
const totalLength = chars.length;
for (let i = 0; i < totalLength; i++) {
const char = chars[i];
const lastElement = i > 0 ? chars[i - 1] : null;
if (!lastElement) {
chars.push(char);
continue;
}
if (lastElement === char) {
cursor = { char, count: cursor ? cursor.count + 1 : 1 };
continue;
} else {
if (cursor) {
const currentCursor = { ...cursor };
cursor = null;
chars.push(...(`${currentCursor.count + 1}`.split('')), char);
continue;
}
}
chars.push(char);
}
for (let i = 0; i < totalLength; i++) {
chars.shift();
}
chars.pop();
return chars.length;
};