From 358fef6a2a857174c9e4d46056c8ca55df1be535 Mon Sep 17 00:00:00 2001 From: Tony K Tan Date: Mon, 22 May 2017 00:37:15 -0700 Subject: [PATCH] rewrite 1.6 to have clearer algorithm and fix bug where original string is not returned in instance of compressed string being same length as original string. --- chapter01/1.6 - String Compression/strComp.js | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/chapter01/1.6 - String Compression/strComp.js b/chapter01/1.6 - String Compression/strComp.js index 2d0e776..3c2d555 100644 --- a/chapter01/1.6 - String Compression/strComp.js +++ b/chapter01/1.6 - String Compression/strComp.js @@ -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