Tuesday, September 1, 2015

String compression

Problem

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.

Note; this if from cracking the coding interview book

Solution


 public String compress(String s)
 {
  if(s.length()==0) return s;

  StringBuffer temp = new StringBuffer();
  Character lastChar = null;
  char currentChar = s.charAt(0);
  int count =1;
  for(int i=1; i< s.length(); i++)
  {
   if(s.charAt(i)==currentChar)
   {
    count++;
   }
   else 
   {
    temp.append(currentChar);
    temp.append(count);
    lastChar = currentChar;
    count = 1;
    currentChar = s.charAt(i);
   }
   System.out.println(temp.toString());
  }
  if(lastChar != currentChar) 
  {
   temp.append(currentChar);
   temp.append(count);
  }
  System.out.println(temp.toString());

  if(temp.length() < s.length())  return temp.toString();
  return s;
 }

No comments:

Post a Comment