Created
December 20, 2012 06:56
-
-
Save Bekt/4343399 to your computer and use it in GitHub Desktop.
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
//http://coolcodebro.blogspot.com/2012/12/string-compression.html | |
public class StringCompression { | |
public static void main(String[] args) { | |
new StringCompression().run(); | |
} | |
void run() { | |
String str = "aabcccccaaa"; | |
String compr = compress(str); | |
System.out.printf("Original: %s (%d)%n", str, str.length()); | |
System.out.printf("Compressed: %s (%d)%n", compr, compr.length()); | |
} | |
String compress(String str) { | |
if(str.length() < 3) | |
return str; | |
StringBuilder compressed = new StringBuilder(); | |
int count = 1; | |
char prev = str.charAt(0), current; | |
for(int i=1; i<str.length(); i++) { | |
current = str.charAt(i); | |
if(current != prev) { | |
compressed.append(prev); | |
compressed.append(count); | |
prev = current; | |
count = 1; | |
} | |
else | |
count++; | |
} | |
//Add the last repeating character | |
compressed.append(prev); | |
compressed.append(count); | |
if(compressed.length() < str.length()) | |
return compressed.toString(); | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment