Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions chapter01/1.6 - String Compression/strComp.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
var strComp = function(string) {
var compressed = '';
var currChar = '';
var currCount = '';
var maxCount = 1;
if (!string || string === '') {
return string;
}

// O(S) time where S is length of string;
// O(S) space, for array will go up to S when string has no consecutive chars

var compressed = [];
var currChar;
var compressedChar;
var compressedCount;
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;
currChar = string.charAt(i);
if (!compressedChar) {
compressedChar = currChar;
compressedCount = 1;
} else if (compressedChar === currChar) {
compressedCount++;
} else {
currCount++;
compressed.push([compressedChar, compressedCount]);
compressedChar = currChar;
compressedCount = 1;
}
}
compressed = compressed + currChar + currCount;
maxCount = Math.max(maxCount, currCount);
compressed.push([compressedChar, compressedCount]);

var answer = compressed.reduce(function(unit) {
return unit + unit[0] + unit[1];
}, '');

return maxCount === 1 ? string : compressed;
return answer.length < string.length ? answer : string;
};

// Test
Expand Down