Count and Say

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, generate the nth term of the count-and-say sequence.

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

Example 1:

Input: 1
Output: "1"
Example 2:

Input: 4
Output: "1211"

题目意思已经挺清楚的了,就是n的结果是根据n-1来推算的,代码如下

public String countAndSay(int n) {
        StringBuilder sb = new StringBuilder("1");
        for(int i = 1; i < n; i++){
            sb = calc(sb.toString());
        }
        return sb.toString();
    }

    private StringBuilder calc(String s){
        /**
         * 循环上一次得到的结果
         * 取得当前index的值与index+1...比较,直到不一样为止
         * 这个个数  count + '当前值' 就是一段
         * 但是我们需要跳过count,然后重复以上过程
         * 得到的每一段都拼接起来得到对于当前n的结果
         * 利用当前n的结果继续调用calc方法推算n+1的结果,如此往复得到最终结果
         */
        StringBuilder sb2 = new StringBuilder("");
        for(int i = 0;i < s.length();i++){
            char a = s.charAt(i);
            int count = 1 ;
            while(i + 1 < s.length()){
                char a_next = s.charAt(i+1);
                if(a_next == a){
                    i ++;
                    count ++;
                }else{
                    break;
                }
            }
            sb2.append(count + "" + a);
        }
        return sb2;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容