Saturday, February 25, 2012

String compression

 public class Compress {  
      public static void compressStr(String str){  
           if(str == null || str.length() < 2){  
                return;  
           }  
           if(countCompression(str) >= str.length()){  
                System.out.println("Should not compress");  
                return;  
           }  
           char[] a = str.toCharArray();  
           int src = 1;  
           int dst = 0;  
           int count = 1;  
           while(src < a.length){  
                if(a[src-1] == a[src]){  
                     count++;  
                }else{  
                     System.out.println("The prev val is "+a[src-1]+" and next val is "+a[src]);  
                     a[dst++] = a[src-1];  
                     a[dst++] = (char) (count + '0');  
                     count = 1;  
                }  
                src++;  
           }  
           System.out.println("The src val is "+src+" and next val is "+count);  
           String compStr = new String(a, 0, dst);  
           compStr = compStr + str.charAt(a.length-1) + count;  
           System.out.println("The compressed str is "+compStr);  
      }  
      public static int countCompression(String str){  
           char[] a = str.toCharArray();  
           int src = 1;  
           int count = 1;  
           int size = 0;  
           while(src < a.length){  
                if(a[src-1] == a[src]){  
                     count++;  
                }else{  
                     size += 1 + String.valueOf(count).length();  
                     count = 1;  
                }  
                src++;  
           }  
           size += 1 + String.valueOf(count).length();  
           System.out.println("The compressed size is "+size);  
           return size;  
      }  
      public static void main(String args[]){  
           compressStr("aabbccccccc");  
      }  
 }  

No comments:

Post a Comment