【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”,把它说出来就是“one one”,写成串就是11,这样就得到了第二个串11;

把第二个串说出来就是“two one”,写成串就是21,这样就得到了第三个串21;

把第三个串说出来就是“one two one one”,写成串就是1211,这样就得到了第四个串1211;

......

题目求的是第n个串。

设置一个StringBuffer存放当前串“说出来的结果”,然后根据n的大小不断循环,最终得到第n个串即可。

代码如下:

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         String accumu = "1";
 4         
 5         while(--n > 0){
 6             StringBuffer sb = new StringBuffer();
 7             char[] faster = accumu.toCharArray();
 8             for(int i = 0;i < faster.length;){
 9                 int count = 1;
10                 char now = faster[i];
11                 i++;
12                 while(i<faster.length && faster[i]== faster[i-1] ){
13                     count++;
14                     i++;
15                 }
16                 sb.append(String.valueOf(count)+now);
17             }
18             accumu = sb.toString();
19         }
20         return accumu;
21     }
22 }

转载于:https://www.cnblogs.com/sunshineatnoon/p/3860018.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值