Write a method called compress that takes a string as input, compresses it using rle, and returns the compressed string. case matters - uppercase and lowercase characters should be considered distinct. you may assume that there are no digit characters in the input string. there are no other restrictions on the input - it may contain spaces or punctuation. there is no need to treat non-letter characters any differently from letters.

Respuesta :

public static String compress (String original) { StringBuilder compressed = new StringBuilder(); char letter = 0; int count = 1; for (int i = 0; i < original.length(); i++) { if (letter == original.charAt(i)) { count = count + 1; } else { compressed = count !=1 ? compressed.append(count) : compressed; compressed.append(letter); letter = original.charAt(i); count = 1; } } compressed = count !=1 ? compressed.append(count) : compressed; compressed.append(letter); return compressed.toString(); }