-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathstrComp.js
More file actions
28 lines (24 loc) · 800 Bytes
/
strComp.js
File metadata and controls
28 lines (24 loc) · 800 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
const stringCompression = (string) => {
let compressed = '';
let currentCharacter = '';
let currentCount = '';
let maxCount = 1;
for(var i = 0; i < string.length; i++) {
if(currentCharacter !== string[i]) {
compressed = compressed + currentCharacter + currentCount;
maxCount = Math.max(maxCount, currentCount);
currentCharacter = string[i];
currentCount = 1;
} else {
currentCount++;
}
}
compressed = compressed + currentCharacter + currentCount;
maxCount = Math.max(maxCount, currentCount);
if(string.length < compressed.length) {
return string;
}
return maxCount === 1 ? string : compressed;
}
console.log('aaaaaa', stringCompression('aabcdef')); // aabcdef
console.log('aaaaaa', stringCompression('aabbcc')); // a2b2c2