Tuesday, August 6, 2013

Coding Exercises Day 4 (Problem #6)

Problem:
Implement a method to perform basic string compression using the counts of repeated characters.  For example, the string aabcccccaaa would become a2b1c5a3.  If the compressed string is no smaller than the original string, the method should return the original string.

String compress(String s) {
  int length = s.length();
  
  if (length < 3) {
    return s;
  }  

  StringBuilder compressed = new StringBuilder();
  
  boolean isCompressed = false;

  char previousChar = s.charAt(0); 
  int charCount = 1;

  int index = 1;

  while (compressed.length() < length && index < length) {
    char currentChar = s.charAt(index);

    if(currentChar != previousChar) {
      compressed.append(previousChar).append(charCount);
      
      previousChar = currentChar;
      charCount = 1;
    }  
    else {
      charCount++;
    }
    index++;
  }

  if (index == length && compressed.length() < length) {
    return compressed.toString;
  }
  return s;
}

No comments:

Post a Comment