码迷,mamicode.com
首页 > 其他好文 > 详细

38. 报数

时间:2019-11-02 17:33:40      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:span   code   nbsp   含义   font   sequence   public   return   seq   

题目描述:

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

标签:span   code   nbsp   含义   font   sequence   public   return   seq   

原文地址:https://www.cnblogs.com/zjuhaohaoxuexi/p/11782995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!