Created
June 15, 2014 22:57
-
-
Save atlas1017/d53c4f08b2a7a942df4e 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
public class compress | |
{ | |
// I assume all the char are asciis | |
// I also assume that all chars appeat less than 10 times | |
public static void main(String[] args) { | |
String s = "safdaaaaaaaa"; | |
String result = compress(s); | |
System.out.println(result); | |
} | |
public static String compress(String s) | |
{ | |
if(!isSmaller(s)) | |
return s; | |
int[] count = new int[256]; | |
char[] result = new char[getlen(s)]; | |
int pos = 0; | |
for(int i = 0; i < s.length(); i++) | |
count[s.charAt(i)]++; | |
for(int i = 0; i < 256; i++) | |
{ | |
if(count[i] > 0) | |
{ | |
result[pos++] = (char)i; | |
result[pos++] = (char)(count[i]+48); | |
} | |
} | |
String sresult = new String(result); | |
return sresult; | |
} | |
public static boolean isSmaller(String s) | |
{ | |
int len = getlen(s); | |
return(len < s.length()); | |
} | |
public static int getlen(String s) | |
{ | |
boolean[] exist = new boolean[256]; | |
int len = 0; | |
for(int i = 0; i < s.length(); i++) | |
exist[s.charAt(i)] = true; | |
for(int i = 0; i < 256; i++) | |
{ | |
if(exist[i]) | |
len += 2; | |
} | |
return len; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment