Implement a method to perform basic string compression using the counts of repeated characters. For example, the string
aabcccccaaa
would becomea2blc5a3
. If the "compressed" string would not become smaller than the original string, your method should return the original string.
Can this be implemented in a better way performance-wise?
package string;
public class CompressChar {
int[] seq = new int [256];
public String compressString(String str){
StringBuffer strComp = new StringBuffer();
for( char c : str.toCharArray()){
seq[c]++;
}
for (char c : str.toCharArray()){
if(seq[c]>0){
strComp.append(c).append(seq[c]);
seq[c]=0;//so that it does not enter , when char occurs again
}
}
if(str.length()<strComp.length()){
return str;
}
return strComp.toString();
}
public static void main(String[] args) {
CompressChar ch = new CompressChar();
System.out.println(ch.compressString("abbcdrfac"));
}
}
temp
variables in theelse
block. Additionally, get rid of the wastedchar[]
initialization by assigningstr.toCharArray()
straight tostrArr
. – Origineil Oct 31 '14 at 15:45