Created
June 18, 2014 21:59
-
-
Save hilda8519/70b9e1c9aecf67189c27 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
import java.util.*; | |
public class compBetter { | |
public static String compBet (String s){ | |
int size=countCompression(s); | |
if(size>s.length()){ | |
return s; | |
} | |
StringBuffer t=new StringBuffer(); | |
int count=1; | |
char tempchart=s.charAt(0); | |
for(int i=1;i<s.length();i++){ | |
if(s.charAt(i)==tempchart){ | |
count++; | |
} | |
else | |
{ | |
t.append(tempchart); | |
t.append(count); | |
tempchart=s.charAt(i); | |
count=1; | |
} | |
} | |
t.append(tempchart); | |
t.append(count); | |
return t.toString(); | |
} | |
static int countCompression(String s){ | |
if(s==null||s.isEmpty()){ | |
return 0; | |
} | |
char tempchart=s.charAt(0); | |
int count=1; | |
int size=0; | |
for(int i=1;i<s.length();i++){ | |
if(s.charAt(i)==tempchart){ | |
count++; | |
} | |
else | |
{ | |
tempchart=s.charAt(i); | |
size+=1+String.valueOf(count).length(); | |
count=1; | |
} | |
size+=1+String.valueOf(count).length(); | |
return size; | |
} | |
return size; | |
} | |
public static void main(String[] args){ | |
{ | |
String s="aaaaabbb"; | |
System.out.println(compBet(s)); | |
System.out.println(s); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment