-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0443-string-compression.js
More file actions
36 lines (30 loc) · 1.06 KB
/
0443-string-compression.js
File metadata and controls
36 lines (30 loc) · 1.06 KB
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
/**
* String Compression
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
var compress = function (chars) {
let writeCurrentIndex = 0;
let scanCurrentIndex = 0;
const originalLength = chars.length;
while (scanCurrentIndex < originalLength) {
const charUnderExamination = chars[scanCurrentIndex];
let groupFirstIndex = scanCurrentIndex;
while (scanCurrentIndex < originalLength && chars[scanCurrentIndex] === charUnderExamination) {
scanCurrentIndex++;
}
let currentGroupCounter = scanCurrentIndex - groupFirstIndex;
chars[writeCurrentIndex] = charUnderExamination;
writeCurrentIndex++;
if (currentGroupCounter > 1) {
const numericString = String(currentGroupCounter);
let digitCharIndex = 0;
while (digitCharIndex < numericString.length) {
chars[writeCurrentIndex] = numericString[digitCharIndex];
writeCurrentIndex++;
digitCharIndex++;
}
}
}
return writeCurrentIndex;
};