swamy
BAN USERprivate void compressUseStringBuffer(String string) {
System.out.println("before compress String:"+string);
System.out.println("before compress size:"+string.length());
int size = countCompress(string);
if(string.length() <size)
{
System.out.println("Actual string is having less size:"+ string);
}
int count = 1;
char last = string.charAt(0);
StringBuffer newString = new StringBuffer();
for(int i=1; i<string.length();i++){
if(string.charAt(i) == last){
count++;
}else{
newString.append(last);
newString.append(count);
last = string.charAt(i);
count = 1;
}
}
newString.append(last);
newString.append(count);
System.out.println("Compressed SB:"+newString);
deCompressUseStringBuffer(newString.toString());
}
private int countCompress(String string) {
char last = string.charAt(0);
int count = 1;
int size = 0 ;
for(int i = 1; i<string.length(); i++){
if(string.charAt(i) == last){
count++;
}else{
last = string.charAt(i);
size += 1 + String.valueOf(count).length();
count = 1;
}
}
size += 1+String.valueOf(count).length();
System.out.println("After Compress size:"+size);
return size;
}
private void deCompressUseStringBuffer(String string) {
System.out.println("before decompress size:"+string.length());
char last = string.charAt(0);
int charCompSize = 1;
StringBuffer newString = new StringBuffer();
for(int i=1; i<string.length();i++){
if(i%2 == 0){
last = string.charAt(i);
}else{
charCompSize = Character.getNumericValue(string.charAt(i));
}
for(int j=0;j<charCompSize;j++){
newString.append(last);
}
charCompSize = 0;
}
System.out.println("After decompress size:"+newString.length());
System.out.println("Decompressed SB:"+newString);
}
- swamy February 10, 2017