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 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.

class Solution {
    public String countAndSay(int n) {
        return count_say("1",1,n);
    }
    public String count_say(String s, int count, int n){
        String str = "";
        int sum = 1;
        char [] ch = s.toCharArray();
        if(count == n) return s;
        for(int i = 0; i < ch.length; i++){
            if(i < ch.length - 1 && ch[i] == ch[i + 1]) sum++;
            else{
                str = str + sum;
                str = str + ch[i];
                sum = 1;
            }
        }
        return count_say(str, count + 1, n);
    }
}

以上就是我在LeetCode 网站所提交的代码。

这道题思路其实很难懂的,查看了网上的资料我才恍然大悟,我觉得吧。。。。就是题目给的例子太少了以至于没办法推测题目的规律。emmmmmmmmm,好了接下来简单概括一下这道题的算法思路吧。

Algorithm analysis:

(就题目的变量而言)当ch[i] == ch[i +1]的时候,然后继续sum + 1;连续有N个相等时,就有"n "+ ch[i]。注意:这里有一个超时的现象,就是当n = ch.length - 1 的时候就不能再执行了,也就是不能再访问数组了,否则就会超时。当ch[i] != ch[i+1]的时候,就有"1" + ch[i],然后再把sum归1重新走下一个(i++)

猜你喜欢

转载自blog.csdn.net/Qgf_666/article/details/82783343