Advertisement
zoltanvi

String compresstion

Jul 9th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. public class Main {
  2.  
  3.     public static void main(String[] args) {
  4.         System.out.println(compress("aaaabbsddddddd"));
  5.  
  6.     }
  7.  
  8.     // String compression
  9.     // aaaabbsddddddd    ==    a4b2sd7
  10.     static String compress(String str) {
  11.         String result = "";
  12.         int i = 0;
  13.  
  14.         int c;
  15.         char prev;
  16.  
  17.         if (str.length() > 0) {
  18.             while(i < str.length()) {
  19.                 c = 1;
  20.                 prev = str.charAt(i);
  21.                 i++;
  22.                 while ((i < str.length()) && (str.charAt(i) == prev)) {
  23.                     c++;
  24.                     i++;
  25.                 }
  26.                 if(c == 1){
  27.                     result += prev;
  28.                 } else{
  29.                     result += prev + "" + c;
  30.                 }
  31.             }
  32.         }
  33.         return result;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement