前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode第38题

LeetCode第38题

作者头像
用户3112896
发布2019-09-26 15:17:15
3830
发布2019-09-26 15:17:15
举报
文章被收录于专栏:安卓圈安卓圈

LeetCode第38题

The count-and-say sequence is the sequence of integers with the first five terms as following:

代码语言:javascript
复制
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:

代码语言:javascript
复制
Input: 1Output: "1"

Example 2:

代码语言:javascript
复制
Input: 4Output: "1211"

翻译:

简单来说就是:

第一次:1

第二次:一个1:11

第三次:两个1:21

第四次:一个2,一个1:1211

第五次:一个1,一个2,两个1:111221

第六次:三个1,两个2,一个1:312211

以此类推...

思路:

首先想想每一次的比较,肯定是首先固定一个数值,然后循环遍历与其相比较

代码语言:javascript
复制
for(int i = 1;i<value.length();i++){   if(temp == value.charAt(i)){       count++;   }else{       //第一次出现不相等       result.append(count).append(temp);       count = 1;       temp = value.charAt(i);   }}

else方法块里的就是关键:一旦出现不相等的情况,就append前面的结果,然后更新那个固定值,接着继续遍历比较

最外面的话很明显就是采用递归了,从1开始,一轮一轮的计算上去,直到想要的结果

代码语言:javascript
复制
String result = "1";while(--n>0){    result = getOnce(result);    System.out.println(result);}

完整代码如下

代码语言:javascript
复制
class Solution {    public String countAndSay(int n) {       String result = "1";        while(--n>0){            result = getOnce(result);            System.out.println(result);        }        return result;            }        public String getOnce(String value){        StringBuffer result = new StringBuffer();        char temp = value.charAt(0);        int count = 1;        for(int i = 1;i<value.length();i++){           if(temp == value.charAt(i)){               count++;           }else{               //第一次出现不相等               result.append(count).append(temp);               count = 1;               temp = value.charAt(i);           }        }        return result.append(count).append(temp).toString();    }}

每次递归打印的结果就是:

11 21 1211 111221 312211

...

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档