Count and Say

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string.

这题难点在于读不懂题目。其实就是要输出第n行字符串。

n=1 输出 1 n=2 之前输出的1 读成1个1,即11 n=3 之前输出的11 读成2个1,即21 n=4 之前输出的21 读成1个2,1个1,即1211 n=5 之前输出的1211,都城1个1,1个2,2个1,即111221 接下来就是求第n行输出

注意的是最终输出的是字符串,并且在循环的时候别忘了末尾那个字符的要加入结果,否则n=1之后就成空字符串了

public String countAndSay(int n) {
    String str = "1";
    if (n <= 0) {
        return null;
    }
    for (int i = 1; i < n; i++) {
        StringBuilder sb = new StringBuilder();
        int count = 1;
        for (int j = 1; j < str.length(); j++) {
            if (str.charAt(j) == str.charAt(j - 1)) {
                count++;
            } else {
                sb.append(count);
                sb.append(str.charAt(j - 1));
                count = 1;
            }
        }
        sb.append(count);
        sb.append(str.charAt(str.length() - 1));
        str = sb.toString();
    }

    return str;
}