LeetCode 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.

网上看了下别人的解释才看懂

1  念成  一个1   11

11   念成两个1   21

21  念成  一个2 一个1   1211

1211  念成 一个1一个2两个1   111221

代码实现

    public String countAndSay(int n) {
        int i=1;
        String result="1";
        while(i<n)
        {
            result=countAndSayString(result);
            i++;
        }
        return result;
    }
    public String countAndSayString(String str)
    {
        if(str.equals("1"))
            return "11";
        char cur=str.charAt(0);//当前数
        int count=1;//当前数个数
        StringBuilder stringBuilder=new StringBuilder();
        for(int i=1;i<str.length();i++)
        {
            if(cur==str.charAt(i))
            {
                count++;
                if(i==str.length()-1)
                {
                    stringBuilder.append(count).append(cur);
                }
            }
            else
            {
                stringBuilder.append(count).append(cur);
                cur=str.charAt(i);
                count=1;
                if(i==str.length()-1)
                {
                    stringBuilder.append(count).append(cur);
                }
            }
        }
        return stringBuilder.toString();
    }
原文地址:https://www.cnblogs.com/maydow/p/4631190.html