-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathstrComp.js
More file actions
46 lines (41 loc) · 1.05 KB
/
strComp.js
File metadata and controls
46 lines (41 loc) · 1.05 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
37
38
39
40
41
42
43
44
45
46
var strComp = function(string) {
var compressed = '';
var currChar = '';
var currCount = '';
var maxCount = 1;
for (var i = 0; i < string.length; i++) {
if (currChar !== string[i]) {
console.log(currChar, string[i], i);
compressed = compressed + currChar + currCount;
maxCount = Math.max(maxCount, currCount);
currChar = string[i];
currCount = 1;
} else {
currCount++;
}
}
compressed = compressed + currChar + currCount;
maxCount = Math.max(maxCount, currCount);
return maxCount === 1 ? string : compressed;
};
// Test
console.log('aaaaaa', strComp('aaaaaa'), 'a6');
console.log('aabcccccaaa', strComp('aabcccccaaa'), 'a2b1c5a3');
//Another solution
function compression(str) {
var counter = 1;
var result = '';
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) === str.charAt(i + 1)) {
counter+=1;
} else {
result += str.charAt(i) + counter.toString();
counter = 1;
}
}
if (result.length < str.length ) {
return result;
} else {
return str;
}
}