Created
August 14, 2014 04:52
-
-
Save pavelnganpi/d2a01d731965cf68234d to your computer and use it in GitHub Desktop.
Run Length Encoding (RLE) is an algorithm for compressing strings, which is specifically useful in compressing binary values. aabccaabaad <--> 2a1b2c2a1b2a1d Implement RLE algorithm for compression and decompression of strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RunLengthEncoding { | |
public static String LRE(String str){ | |
StringBuilder test = new StringBuilder(); | |
int count = 1; | |
char[] chars = str.toCharArray(); | |
for(int i=0;i<chars.length;i++){ | |
char c = chars[i]; | |
while( i+1<chars.length && c == chars[i+1]){ | |
count++; | |
i++; | |
} | |
test.append(count).append(c); | |
count = 1; | |
} | |
return test.toString(); | |
} | |
public static String deCompression(String str){ | |
StringBuilder test =new StringBuilder(); | |
char[] chars = str.toCharArray(); | |
int n = chars.length; | |
for(int i = 0;i<n;i=i+2){ | |
char d =chars[i]; | |
int a = Character.getNumericValue(d); | |
char b = chars[i+1]; | |
for(int j=0;j<a;j++){ | |
test.append(b); | |
} | |
} | |
return test.toString(); | |
} | |
public static void main(String[]args){ | |
String test = "aabccaabaad"; | |
System.out.println(LRE(test)); | |
System.out.println(deCompression("2a1b2c2a1b2a1d")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment