【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 }
复制代码
posted @   SunshineAtNoon  阅读(219)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示