LeetCode算法系列:38. Count and Say

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82181212

题目描述:

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个元素),将元素的数目和值依次加入新的字符串中

具体算法如下

class Solution {
public:
    string countAndSay_Recursive(string s){
        string res = "";
        int j = 0;
        for(int i = 0; i< s.length();)
        {
            while(i< s.length() && s[i + 1] == s[i]) i ++;
            res += i + 1 - j + '0';
            res += s[i ++];
            j = i;
        }
        return res;
    }
    string countAndSay(int n) {
        string s = "1";
        if(n == 0)return "";
        if(n == 1)return s;
        for(int i = 2; i <= n; i ++){
            s = countAndSay_Recursive(s);
        }
        return s;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82181212