-2

How to count the characters only if they are right next to each other, otherwise just print the characters as they are. I wrote the following code based on my little knowledge of Java.

for example String w="kjiikkkjial";

the result should be: kji2k3jial

    String am ="asbbaamkkkjkssg";
    char op = 0;

    char[] ch = am.toCharArray();
    for(int i=0; i<ch.length; i++) {
        int k=1;
        for(int j=i+1; j<ch.length; j++) {
            if(ch[i]==ch[j]) {
               k++;
               op=ch[j];    
               i=j;
            }
            else  break;
        }
        if(k>1)
            System.out.print(op+""+k);
        else
            System.out.print(ch[i]);    
    }
Mukesh A
  • 323
  • 1
  • 4
  • 13

1 Answers1

0

This should work, call this function with the input as your string and it will return the expected output.

public static String runLengthEncoding(String text) {
    String encodedString = "";

    for (int i = 0, count = 1; i < text.length(); i++) {
        if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1))
            count++;
        else {
            encodedString = encodedString.concat(Character.toString(text.charAt(i)));
            if(count>1) {
                encodedString = encodedString.concat(Integer.toString(count));
            }
            count = 1;
        }
    }
    return encodedString;
}

This is a link to the working example on ideone.

Mukesh A
  • 323
  • 1
  • 4
  • 13
  • my code is working too, can you please tell what is wrong with my logic? – LaterHomie Sep 08 '18 at 09:07
  • you are using 2 loops, first to iterate over the string, without comparing, and the second loop to compare, which you could have at the same place like what I have done in my answer, the solution may be correct but it's not efficient. – Mukesh A Sep 08 '18 at 09:12