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, 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数的特征,没找见,尴尬。
最直观的想法就是一点点从第一个数据往下算过去,这样的时间复杂度肯定是比较大的,但暴力的方法总能解决问题。
计算的核心问题是如何根据第i个count and say数c[i]得到第i+1个count and say数c[i+1],最简单的办法就是从头对c[i]的每位数进行计数,如果相同那么count加一,如果不同将这位数及count值推入结果。
最后进行循环即可。(或者迭代效果更好?)
最终代码如下:
class Solution {
    public String countAndSay(int n) 
    {
        String s="1";//初始化
        for(int i=1;i<n;i++)
        {
            s=change(s);//循环下去
        }
        return s;
    }
    static String change(String s)//对于一个输入的序列得到下一个序列
    {
        StringBuilder res=new StringBuilder();
        int length=s.length();
        int count=1;
        char temp1=s.charAt(0);
        for (int i=1;i<length;i++)
        {
            if(s.charAt(i)==temp1)//判断相同计数
                count++;
            else//判断不同,缓存
            {
                res.append(count);
                res.append(temp1);
                temp1=s.charAt(i);
                count=1;
            }
        }
        res.append(count);//当长度为1和最后一位的数据存入缓存
        res.append(temp1);
        return res.toString();
    }
}
最后消耗时间只超过38%的提交者,表示这个算法意料之内远远没有达到最优。

转载于:https://www.cnblogs.com/Einsler/p/7608700.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值