Skip to content

Instantly share code, notes, and snippets.

@atlas1017
Created June 15, 2014 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atlas1017/d53c4f08b2a7a942df4e to your computer and use it in GitHub Desktop.
Save atlas1017/d53c4f08b2a7a942df4e to your computer and use it in GitHub Desktop.
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