【leetcode】38. 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 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

思路

先用中文解释一下题目吧。
就像题目中说的那样:
“1”读作“1个1”,因而写作“11”,这是第二行,而“1”是第一行;
而第二行的"11"读作“2个1”,因而第三行写作“21”;
第三行读作“1个2,1个1”,写作“1211”;
……
这样应该就差不多了,第n行要用到第n-1行的结果,遍历第n-1行的结果,根据上面的规则即可得到答案。
这样就有下面两个问题:
1.第n-1行结果怎么来,我的解决方案是递归;
2.怎么利用规则和n-1行的结果得到第n行结果,这里首先要定义n=1时的结果,在编码过程中,我发现按照我的代码n=2时求解也需要预先定义,于是也定义了n=2时的结果。然后从n-1结果的第二个字符开始遍历就可以了。

代码

我自己的代码效率还是比较低,17%左右吧。
public String countAndSay(int n) {
    if (n == 1) {
        return "1";
    }
    if (n == 2) {
        return "11";
    }
    String res = "";
    String pre_res = countAndSay(n-1);
    int count = 1;
    char temp = pre_res.charAt(0);
    for (int i = 1;i < pre_res.length();i++) {
        if (pre_res.charAt(i) == temp) {
            count++;
        }else {
            res += String.valueOf(count) + temp;
            temp = pre_res.charAt(i);
            count = 1;
        }
    }
    res += String.valueOf(count) + temp;
    return res;
}


猜你喜欢

转载自blog.csdn.net/sinat_22481983/article/details/76819214