[text] RLE

Viewer

  1. public class RLE_encoding {
  2.     public static void printRLE(String str)
  3.     {
  4.         int n = str.length();
  5.         for (int i = 0; i < n; i++) {
  6.  
  7.             // Count occurrences of current character
  8.             int count = 1;
  9.             while (i < n - 1 &&
  10.                    str.charAt(i) == str.charAt(i + 1)) {
  11.                 count++;
  12.                 i++;
  13.             }
  14.  
  15.             // Print character and its count
  16.             if(count<3) {
  17.             
  18.                     System.out.print(0);
  19.                     System.out.print(str.charAt(i));
  20.             }else {
  21.                    
  22.                     System.out.print(count);       
  23.                     System.out.print(str.charAt(i));
  24.             }
  25.             
  26.             
  27.         }
  28.         System.out.println();
  29.     }
  30.  
  31.     public static void main(String[] args)
  32.     {
  33.         String Ch1 = "ABABABABABABABABABABABABABABABABABAB";
  34.         printRLE(Ch1);
  35.         
  36.         String Ch2 = "AAAAAABBBBBBAAAAAABBBBBBAAAAAABBBBBB";
  37.         printRLE(Ch2);
  38.         
  39.         String Ch3 = "AAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBB";
  40.         printRLE(Ch3);
  41.         
  42.    
  43.     }
  44. }

Editor

You can edit this paste and save as new:


File Description
  • RLE
  • Paste Code
  • 05 May-2021
  • 1.11 Kb
You can Share it: