Search code examples
javastringrun-length-encoding

Splitting this string to get the max count to a corresponding character


I am currently implementing Run Length Encoding for text compression and my algorithm does return Strings of the following form:

Let's say we have a string as input

"AAAAABBBBCCCCCCCC"

then my algorithm returns

"1A2A3A4A5A1B2B3B4B1C2C3C4C5C6C7C8C"

Now I want to apply Java String split to solve this, because I want to get the highest number corresponding to character. For our example it would be

"5A4B8C"

My function can be seen below

public String getStrfinal(){

    String result = "";
    int counter = 1;
    StringBuilder sb = new StringBuilder();
    sb.append("");
    for (int i=0;i<str.length()-1;i++) {
        char c = str.charAt(i);
        if (str.charAt(i)==str.charAt(i+1)) {
            counter++;
            sb.append(counter);
            sb.append(c);
        }
        else {
            counter = 1;
            continue;
        }
    }
    result = sb.toString();
    return result;
}

Solution

  • public static String getStrfinal(){
    
        StringBuilder sb = new StringBuilder();
    
        char last = 0;
        int count = 0;
        for(int i = 0; i < str.length(); i++) {
    
            if(i > 0 && last != str.charAt(i)) {
                sb.append(count + "" + last);
                last = 0;
                count = 1;
            }
            else {
                count++;
            }
    
            last = str.charAt(i);
    
        }
        sb.append(count + "" + last);
        return sb.toString();
    }