Leetcode——38. Count and Say

题目原址

https://leetcode.com/problems/count-and-say/description/

题目描述

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.

Example1:

Input: 1
Output: “1”

Example2:

Input: 4
Output: “1211”

解题思路

该题的题目描述简直太烂了!!!

题目的大意应该是这样的:
(1)当n等于1时,输出“1”;
(2)当n等于2时,要看n-1中输出的信息,将输出的信息用口语读出来,口语读的结果作为n=2的输出值,(因为n=1时输出1,所以,口语读的结果是:1个1,所以n=2的输出结果是:11)
(3)当n等于3时,要看n-1中输出的信息,将输出的信息用口语读出来,口语读的结果作为n=3的输出值,(因为n=2时输出11,所以,口语读的结果是:2个1,所以n=3的输出结果是:21)
(4)当n等于4时,因为n=3时输出21,所以口语读的结果是:1个2,1个1,所以n=4的输出结果是1211
(5)当n等于5时,因为n=4时输出1211,所以口语读的结果是:1个1,1个2,2个1,所以n=5的输出结果是111221
(6)。。。以此类推

所以就将上述步骤转变为代码就可以解决该题了

因为当前的结果依赖于前面的输出结果,所以要记录前面的输出结果,就是递归!

AC代码

class Solution {
    public String countAndSay(int n) {
            String s = "1";
            for(int i = 1; i < n; i++) {
                s = count(s);
            }
            return s;
    }

    String count(String s) {
        StringBuffer sb = new StringBuffer();
        char c = s.charAt(0);
        int count = 1;
        for(int i = 1; i < s.length(); i++) {
            if(s.charAt(i) == c) 
                count++;
            else {
                sb.append(count);
                sb.append(c);
                c = s.charAt(i);
                count = 1;
            }
        }
        sb.append(count);
        sb.append(c);
        return sb.toString();
    }
}

感谢

https://leetcode.com/problems/count-and-say/discuss/16040/Straightforward-Java-Solution

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值