Tuesday, June 9, 2015

Q.5 - 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.

public class StringCompression{
   public static void main(String args[]){
      System.out.println(new StringCompression().compressString("cccconnttttttiiiinnnummmmmmmmmmm")); //c4o1n2t6i4n3m11
      System.out.println(new StringCompression().compressString("Ashish")); //Ashish
}

  public String compressString(String str){
      String newString = "";
      char curr = ' ',prev = ' ';
      int count = 0;

      curr = str.charAt(0);
   
      for(int i=0 ; i<str.length() ; i++)
      {
         prev = curr;
         curr = str.charAt(i);
         if(prev == curr)
           count++;
 else
 {
    newString = newString + prev + String.valueOf(count);
    count = 1;
 }
      }

newString = newString + prev + String.valueOf(count);

if(!(newString.length() < str.length()))
   return str;
return newString;
   }
}

_______________________________________________________________________

Output:
c4o1n2t6i4n3u1m11
Ashish

No comments:

Post a Comment