Tell me how to improve the existing code:

public class RLE { public static String encode(String s) { if (s == "" || s == null) return ""; StringBuilder sb = new StringBuilder(); int count = 1; char previous = s.charAt(0); char current; for (int i = 1; i < s.length(); i++) { current = s.charAt(i); if (current == previous) { count++; } else { if (count == 1) { sb.append(previous); } else if (count > 1) { sb.append(count).append(previous); count = 1; } } previous = current; } return sb.toString(); } 

Now the result of the compression 'Heeeeeeeeeeeellooooo' -> H12e2l

The expected result with the condition: the number of letters in the repetition is more than nine, there must be two combinations of the letter number 'Heeeeeeeeeeeellooooo' -> H9e3e2l5o

  • instead of if (s == "" || s == null) return ""; if (s == null || "".equals(s)) return ""; - JVic
  • Can, just if (current == previous) add to if ((current == previous) && (count < 9)) ? - Akina
  • I do not understand why in the line H9e3e2l5o in a row 2 abbreviations with the symbol 'e'? - dgzargo

1 answer 1

you do not pass the "last" cycle: when the "previous" element is, and the current is not
you can either change the loop so that it goes through 1 more iterations
or add the code after the loop (you will have to duplicate part of the code)

  • if you want a maximum of 9 abbreviations, add if (current == previous) check if (count>8) ... processing this case - dgzargo