首页 > 代码库 > [Leetcode] count and say 计数和说

[Leetcode] count and say 计数和说

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integer n, generate the n th sequence.

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

题意:返回第n个序列,第i+1个字符串是第i个字符串的读法。参考:Grandyang和JustDoIT的博客。

思路:算法就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。代码需要两个循环,第一个是为找到第n个,第二是为了,根据上一字符串的信息来实现当前的字符串。

 1 class Solution {
 2 public:
 3     string countAndSay(int n) 
 4     {
 5         if(n<1) return NULL;
 6 
 7         string res="1";
 8         for(int i=1;i<n;++i)
 9         {
10             string temp;    //当前序列
11             res.push_back(*);
12             int count=0;    //重复的个数
13             for(int j=0;j<res.size();++i)
14             {
15                 if(j==0)
16                     count++;
17                 else
18                 {
19                     if(res[j] !=res[j-1])
20                     {
21                         temp.push_back(count+0);
22                         temp.push_back(res[j-1]);
23                         count=1;
24                     }
25                     else
26                         ++count;
27                 }    
28             }
29             res=temp;  
30         }
31         return res;
32     }
33 };

[Leetcode] count and say 计数和说