2014年5月11日星期日

Recursive and Loop Solution - Count and Say

The formula is to count the previous result (n - 1), how many 1s and 0s. The the problem is converted to count an array as below. Set pre and count, then loop the array to update count and pre. After the loop to add one more time. return the result.

public class Solution {
    public String countAndSay(int n) {
        if(n == 1){
            return String.valueOf(1);
        }
        StringBuilder sb = new StringBuilder();
        char[] lastResult = countAndSay(n - 1).toCharArray();
        int k = 1;
        int count = 1;
        char preChar = lastResult[0];
        while(k < lastResult.length){
            if(lastResult[k] == preChar){
                count++;
            }else{
                sb.append(String.valueOf(count));
                count = 1;
                sb.append(String.valueOf(preChar));
                preChar = lastResult[k];
            }
            k++;
        }
        sb.append(String.valueOf(count));
        sb.append(String.valueOf(preChar));
       
        return sb.toString();
    }
}

没有评论: