美文网首页
LeetCode 38. Count and Say

LeetCode 38. Count and Say

作者: cb_guo | 来源:发表于2019-04-09 11:37 被阅读0次

题目描述

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.
Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

题目解读

初始值第一行是 1。
第二行读第一行,1 个 1,去掉个字,所以第二行就是 11。
第三行读第二行,2 个 1,去掉个字,所以第三行就是 21。
第四行读第三行,1 个 2,1 个 1,去掉所有个字,所以第四行就是 1211。
第五行读第四行,1 个 1,1 个 2,2 个 1,去掉所有个字,所以第五航就是 111221。
第六行读第五行,3 个 1,2 个 2,1 个 1,去掉所以个字,所以第六行就是 312211。
然后题目要求输入 1 - 30 的任意行数,输出该行是啥。

题目思路

  • 思路一、
class Solution {
public:
    string countAndSay(int n) {
        string result = "";
        string tt = "1";
        
        if(n == 1){
            return tt;
        }
        
        // 迭代几行
        while(n > 1){
            n = n - 1;
            
            int len = tt.size();
            int i = 0, j = 0;
            
            while(i < len){
                int count = 1;
                j = i+1;
                while(j < len && tt[j]==tt[i]){
                    j = j + 1;
                    count = count + 1;
                }
                result.append(to_string(count));
                // 此处注意 tt[i]-'0' ,要不然会有问题的
                result.append(to_string(tt[i] - '0'));
                i = j;
            }
            tt = result;
            result = "";
        }
        return tt;
    }
};

总结展望

相关文章

网友评论

      本文标题:LeetCode 38. Count and Say

      本文链接:https://www.haomeiwen.com/subject/vptbiqtx.html