38. 报数

Posted zjuhaohaoxuexi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了38. 报数相关的知识,希望对你有一定的参考价值。

题目描述:

The count-and-say sequence is the sequence of integers
beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

代码:

 

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4 
 5         if(n<=1)
 6             return "1";
 7         string cur = "1";
 8         string next = "";
 9         int k = 1;//k的含义为已经产生的序列的个数
10         while(k<n)
11         {   
12             int len = cur.length();
13             int i =0;
14             while(i<len)
15             {
16                 char c = cur[i];
17                 int cnt = 1;
18                 int j = i+1;
19                 while(j<len && cur[j]==c)//这里不是一个一个的判断
20                 {                    //而是一次操作将满足条件的都判断完
21                     cnt++;
22                     j++;
23                 }
24                 next+=to_string(cnt)+c;
25     
26                 i=j;
27             }
28             cur = next;
29             k++;
30             next = "";
31         }
32         return cur;       
33     }
34 
35 };

 

以上是关于38. 报数的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode38.报数

LeetCode38.报数

LeetCode 38. 报数

leetcode算法-简单38. 报数

LeetCode刷题记录_38. 报数

38. 报数