|
| 1 | +package medium; |
| 2 | + |
| 3 | +/** |
| 4 | + * Have the function RunLength(str) take the str parameter being passed |
| 5 | + * and return a compressed version of the string using the Run-length encoding algorithm. |
| 6 | + * --- |
| 7 | + * This algorithm works by taking the occurrence of each repeating character |
| 8 | + * and outputting that number along with a single character of the repeating sequence. |
| 9 | + * --- |
| 10 | + * For example: "wwwggopp" would return 3w2g1o2p. |
| 11 | + * The string will not contain any numbers, punctuation, or symbols. |
| 12 | + */ |
| 13 | +public class RunLength { |
| 14 | + |
| 15 | + /** |
| 16 | + * Run Length function. |
| 17 | + * |
| 18 | + * @param str input string |
| 19 | + * @return a compressed version of the string |
| 20 | + */ |
| 21 | + private static String runLength(String str) { |
| 22 | + StringBuilder output = new StringBuilder(); |
| 23 | + int count = 0; |
| 24 | + char prev = str.charAt(0); |
| 25 | + for (int i = 0; i < str.length(); i++) { |
| 26 | + if (str.charAt(i) == prev) { |
| 27 | + count++; |
| 28 | + } else { |
| 29 | + output.append(count).append(prev); |
| 30 | + count = 1; |
| 31 | + prev = str.charAt(i); |
| 32 | + } |
| 33 | + } |
| 34 | + output.append(count).append(prev); |
| 35 | + return output.toString(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Entry point. |
| 40 | + * |
| 41 | + * @param args command line arguments |
| 42 | + */ |
| 43 | + public static void main(String[] args) { |
| 44 | + var result1 = runLength("ultrarevolutionaries"); |
| 45 | + System.out.println(result1); |
| 46 | + var result2 = runLength("underworld"); |
| 47 | + System.out.println(result2); |
| 48 | + } |
| 49 | + |
| 50 | +} |
0 commit comments