Skip to content

Instantly share code, notes, and snippets.

@asdw3276
Last active August 29, 2015 14:02
Show Gist options
  • Save asdw3276/8da1d8560fe3897442d8 to your computer and use it in GitHub Desktop.
Save asdw3276/8da1d8560fe3897442d8 to your computer and use it in GitHub Desktop.
1.5
public class stringcompress{
public static void main(String[] args)
{
String test = "aaabbccddaaaaaabba";
String result = compress(test);
System.out.println(result);
}
public static String compress(String s)
{
if(s.equals(null))
return null;
if(s.length() <= 2)
return s;
int length = s.length();
char cur = s.charAt(1);
char pre = s.charAt(0);
int count = 1;
String result = s.substring(0,1);
for(int i = 1; i < length; i++)
{
cur = s.charAt(i);
if(count == 0)
{
result = result.concat(Character.toString(cur));
count++;
}
if(cur == pre)
{
count++;
pre = cur;
if(i == length - 1)
result = result.concat(Integer.toString(count));
}
else
{
result = result.concat(Integer.toString(count));
count = 0;
pre = cur;
if(i == length - 1)
{
result = result.concat(s.substring(i,i+1));
result = result.concat(Integer.toString(1));
}
}
}
if(result.length() >= s.length())
return s;
else
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment