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

 

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

就是让我们输入n,输出count-and-say序列的第n个字符串。

解决问题,核心是要从最小规模的问题找到一般的规律。

这道题的规律是:第n个字符串是对第n-1个字符串的描述。

问题转化为:得到第一个字符串,以此为基础,迭代产生第n个字符串。

package com.blackfish.bill.algorithm;

public class CountAndSay {

    public static String countAndSay(int n) {

        if(n <= 0) {
            return "";
        }
        if(n == 1) {
            return "1";
        }
        if(n == 2) {
            return "11";
        }
        //因为使用双指针,需要从第三个字符串开始
        String initStr = "11";
        int loop = 0;
        //迭代产生字符串
        while(loop < n - 2) {
            initStr = generateStr(initStr);
            loop++;
        }
        return initStr;
    }

    public static String generateStr(String str) {
        if(str == null || str.equals(""))
            return "";

        int len = str.length();
        //双指针
        int i = 0;
        int j = 1;
        //一个数字连续出现的次数,至少出现一次
        int charCnt = 1;
        String result = "";
        while(i < j && j < len) {
            if(j == len - 1) {
                if(str.charAt(i) == str.charAt(j)) {
                    charCnt++;
                    return result + charCnt + str.charAt(i);
                } else {
                    return result + charCnt + str.charAt(i) + "1" + str.charAt(j);
                }
            }
            if(str.charAt(i) == str.charAt(j)) {
                //i不动,j移动
                j++;
                charCnt++;
            } else {
                result = result + charCnt + str.charAt(i);
                charCnt = 1;
                //步子迈的有点大
                i = j;
                j++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
//        String str = "1211";
//        String gStr = CountAndSay.generateStr(str);
//        System.out.println(gStr);
        System.out.println(CountAndSay.countAndSay(7));
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值