Question: 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;
}

```

Answer: 
```
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();
}

```
Instead of string Buffer you can use a map it will be much easier and clean to do so.

```
public static void main(String[] args)  {   
    String input = "AAAAABBBBCCCCCCCCAAABBBDDCCCC";
    int counter=1;
    for(int i=1; i<input.length(); i++) {
        if(input.charAt(i-1)==input.charAt(i)) {
            counter=counter+1;
        }else if(input.charAt(i-1)!=input.charAt(i)){
            System.out.print(counter+Character.toString(input.charAt(i-1)));
            counter=1;
        }if(i==input.length()-1){
            System.out.print(counter+Character.toString(input.charAt(i)));
        }
    }   
}

```

This will gives 

```
5A4B8C3A3B2D4C

```

**UPDATES**  

I Agree with @WJS if the string contains number the out put becomes messy 
hence if the System.out in above code will be exchange with below i.e.

```
System.out.print(Character.toString(input.charAt(i-1))+"="+counter+" ");

```

then for input like 

```
AAAAABBBBCCCCCCCCAAABBBDD556677CCCCz

```

we get out put as below

```
A=5 B=4 C=8 A=3 B=3 D=2 5=2 6=2 7=2 C=4 z=1

```