codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Cracking The Coding Interview] 1.6: String Compression #9

Open jtkaufman737 opened 5 years ago

jtkaufman737 commented 5 years ago

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

//aabcccccaaa //a2blc5a3

jtkaufman737 commented 5 years ago
function compressMe(str){
  let currCount = 1, result = "";

  for(var i=0; i < str.length; i++) {
    if(str[i] === str[i + 1]) { 
      // all we are looking at are strings of sameness
      currCount ++;
    } else { 
      // and if that pattern breaks, we take a snapshot & move on
      result += str[i] + currCount;
      currCount = 1;
   }
  }

str < result ? console.log("Original is compressed: " + str) : console.log("Compressed string is :" + result);
}

compressMe("aabbcccddddeeeeeaa");
compressMe("aaa");
compressMe("aaaabbbbccccaaa");
compressMe("a");