Q1.5 no need to count compression size when using StringBuffer
In Q1.5, solution compressBetter, since StringBuffer does not have a prefix size, do we still need to check the size of the compressed string before building it up?
we can compare the size of the buffer with the original string while building up the new string. If the length of the new string exceeds the original one, then return the original string.
Here's my code:
public static String compress(String str) {
if(str.length()<=2) {
return str;
}
StringBuffer mystr = new StringBuffer();
char last = str.charAt(0);
int count = 1;
for(int i=0;i<str.length();i++){
if(str.charAt(i) == last) {
count++;
} else {
mystr.append(last);
mystr.append(count);
last = str.charAt(i);
count =1;
}
if(mystr.length() >= str.length()) {
return str;
}
}
mystr.append(last);
mystr.append(count);
return mystr.toString();
}
I have the same thought. I think we just need to compare the result mystr.toString().length with original string length. The time complexity of those two method should be the same. Moreover, using countCompression in the case that the result will be shorter than the original one, we would need to go for one more for loop. Though it's not a big problem in the scale of complexity, it may not a better answer.
- Suzy May 13, 2015