-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathstrComp.js
More file actions
67 lines (57 loc) · 1.77 KB
/
Copy pathstrComp.js
File metadata and controls
67 lines (57 loc) · 1.77 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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');
// variant
function compress(inputString) {
if (inputString.length <= checkCompressionLength(inputString))
return inputString;
function doCompression(inputString) {
countConsecutive = 0;
compressString = '';
for (var i = 0; i < inputString.length; i++) {
countConsecutive++;
if (inputString[i] !== inputString[i + 1]) {
compressString += inputString[i];
compressString += countConsecutive;
countConsecutive = 0;
}
}
return compressString;
}
function checkCompressionLength(inputString) {
countCompressedLength = 0;
countConsecutive = 0;
for (var i = 0; i < inputString.length; i++) {
countConsecutive++;
if (inputString[i] !== inputString[i + 1]) {
countConsecutive = 0;
countCompressedLength += (1 + countConsecutive.toString().length);
}
}
return countCompressedLength;
}
return doCompression(inputString);
}
console.log('aaaaaa', compress('aaaaaa'), 'a6');
console.log('abc', compress('abc'), 'abc');
console.log('aabcccccaaa', compress('aabcccccaaa'), 'a2b1c5a3');