Wednesday, June 19, 2013

cc150_1.5

Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string aabcccccaaa would become
a2blc5a3. If the "compressed" string would not become smaller than the original
string, your method should return the original string.

//use StringBuffer to avoid useless copying
public String compressBad(String str){
   int  count = 1, n = str.length();   if(n == 0) return null;
   StringBuffer res =new StringBuffer(); 
   for(int i = 1; i < n; i++){
      if(str.charAt(i) == str.charAt(i-1)){
          count++;
      }
     else {
          res.append(str.charAt(i-1));
          res.append(count);
          count = 1;
   }
 res.append(str.charAt(n-1));
 res.append(count);
 String cp = res.toString();
 if(cp.length() < n) return cp;
 else return str.
}

//if don't use StringBuffer, first figure out the new size, then do backtracking to get desired string from a new char array.

No comments:

Post a Comment