LeetCode38

来源:互联网 发布:怎样淘宝网上买东西 编辑:程序博客网 时间:2024/06/07 16:56

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

Input: 1

Output: “1”

Input: 4

Output: “1211”

中文介绍

一开始我没看到这道题到底想要我们干什么,我以为是跟队列训练的口号一样呢,121,121。。没想到完全不是,后来看了网上一些人的解释也是云里雾里的,最后还是看了好几遍才明白过了。原谅我的语言水平。

这道题就是给定一个数字,输出从1开始的口语念法。
1. 比如 1的口语念法,就是 1个1(也就是题目中的one 1)形成11.
2. 然后 11的口语念法是 2个1(也就是题目中的two 1s)形成21.
3. 然后 21的口语念法是 1个2 1个1(也就是题目中的 “one 2, then one 1”)形成1211
4. 然后 1211的口语念法是 1个1 1个2 两个1 ,形成的是111211
5. 然后 111211 形成的 311221

就这样不停的循环下去。给定的输入数字也就是第几步的输出,当然在这个题目里面n=0的时候输出的是1.

从上面的介绍就可以写出递归的代码

public class Solution38{    public static  void main(String[] args){        Solution38 solution = new Solution38();        System.out.println(solution.countAndSay(4));    }    public String countAndSay(int n) {        if(n<2){            return "1";        }        return helper("1", 2, n).toString();    }    public StringBuffer helper(String str,int i,int limit){        if(i>limit){            return new StringBuffer(str);        }        char pre = str.charAt(0);        char m = '1';        StringBuffer result = new StringBuffer();        for(int j =1;j<str.length();j++){            if(str.charAt(j)==pre) m++;            else {                result.append(m);                result.append(pre);                pre = str.charAt(j);                m='1';            }        }        result.append(m);        result.append(pre);        return helper(result.toString(), i+1, limit);    }}

这道题目还算是比较简单的,其中比较关键的就是如何理解这道题的含义。(果然程序员还是要明白客户的需求,不要随便搞。哈哈)
LeetCode学习系列Github,持续更新
https://github.com/yanqinghe/leetcode

原创粉丝点击