Zip String. aaabbbb ->3a4b - Java Algorithm

Java examples for Algorithm:String

Description

Zip String. aaabbbb ->3a4b

Demo Code


public class Main {
  
  public static void main(String[] args) {
   /*w  ww .j  a  v  a  2  s .c  o m*/
    System.out.println(zipString("aaaa baccccc") );
  }
  
  public static String zipString(String str){
    String result = "";
    
    char[] chrArr = str.toCharArray();
    
    int cnt = 0;
    
    char chr = chrArr[0];
    
    for(int i = 0; i < chrArr.length; i++){
      
      if(chr == chrArr[i]){
        cnt++;
      }else{
        
        result += cnt + (chrArr[i - 1] + "");
        
        cnt = 1;
        
        chr = chrArr[i];
      }
    }
    
    return result + cnt + chr;
    
  }

}

Related Tutorials