package algorithm.lintcode.easy;

public class CountAndSay {
    //TODO refactor
    public String countAndSay(int n) {
        return countAndSay("1", n - 1);
    }

    private String countAndSay(final String say, final int time) {
        if(time == 0) {
            return say;
        }
        char last = '0';
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for(int i = 0, len = say.length(); i < len; i++) {
            if(say.charAt(i) == last) {
                count ++;
            }else {
                if(count > 0) {
                    sb.append(count).append(last);
                }
                last = say.charAt(i);
                count = 1;
            }
            if(i == len - 1) {
                sb.append(count).append(last);
            }
        }
        return countAndSay(sb.toString(), time - 1);
    }
}

@@ -58,28 +58,8 @@
 y %7B%0A
-    //TODO refactor%0A
     
@@ -217,16 +217,17 @@
       if
+ 
 (time ==
@@ -278,332 +278,289 @@
     
-char last = '0';%0A        int count = 0;%0A        StringBuilder sb = new StringBuilder(
+return countAndSay(sayOnce(say.substring(1), %22%22, say.charAt(0), 1), time - 1
 );%0A    
+%7D%0A%0A
     
-for(int i = 0, len = say.length(); i %3C len; i++) %7B%0A            if(say.charAt(i) == last) %7B%0A                count ++;%0A            %7Delse %7B%0A                if(count %3E 0) %7B%0A                    sb.append(count).append(last)
+private String sayOnce(final String remainStr, String haveSay, final char lastChar, int charCount) %7B%0A        if (remainStr.length() == 0) %7B%0A            return haveSay + charCount + lastChar
 ;%0A
-        
     
@@ -577,170 +577,169 @@
     
- 
-       last = say.charAt(i);%0A                count = 1;%0A            %7D%0A            if(i == len - 1) %7B%0A                sb.append(count).append(last);%0A            %7D
+if (remainStr.charAt(0) == lastChar) %7B%0A            charCount++;%0A        %7D else %7B%0A            haveSay = haveSay + charCount + lastChar;%0A            charCount = 1;
 %0A   
@@ -764,43 +764,79 @@
 urn 
-countAndSay(sb.toS
+sayOnce(remainStr.subs
 tring(
+1
 ), 
-time - 1
+haveSay, remainStr.charAt(0), charCount
 );%0A 

Refactor count and say