Count and Say(报数)

http://www.lintcode.com/zh-cn/problem/count-and-say/#

public class Solution {
    /*
     * @param n: the nth
     * @return: the nth sequence
     */
    public String countAndSay(int n) {
        // write your code
//        用来记录每次的结果
        StringBuilder sb = new StringBuilder();
//        第一次运算
        sb.append(1);
        int i = 1;
//        循环n-1次
        while (i < n) {
//            把上一次的结果记录下来
            char[] chars = sb.toString().toCharArray();
//            清空用来记录这次的结果
            sb = new StringBuilder();
            int j = 0;
            while (j < chars.length) {
                int k = j + 1;
                int count = 1;
//                找当前元素后边跟当前元素相同的,一直找到不同的为止
                while (k < chars.length && chars[j] == chars[k]) {
                    count++;
                    k++;
                }
                sb.append(count).append(chars[j]);
                j += count;
            }
            i++;
        }
        return sb.toString();
    }
}

你可能感兴趣的:(Count and Say(报数))