Leetcode 38 Count and Say

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83894242

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

这个题目的意思就是此时的字符串由上一个字符串来定义,也就是count+say,代码如下:

class Solution {
    public String countAndSay(int n) {
        StringBuffer cur = new StringBuffer("1");
        StringBuffer prev;
        int count = 0;
        char say;
        for(int i = 1 ; i < n ; i++){
            prev = cur;
            cur = new StringBuffer();
            count = 1;
            say = prev.charAt(0);
            for(int j = 1,len = prev.length() ; j < len;j++){
                if(prev.charAt(j) != say){
                    cur.append(count).append(say);
                    count = 1;
                    say = prev.charAt(j);
                }else{
                    count++;
                }
            }
            cur.append(count).append(say);
        }
        return cur.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/Neo233/article/details/83894242