首页 > 其他 > 详细

[Leetcode] count and say 计数和说

时间:2017-06-20 17:07:57      阅读:287      评论:0      收藏:0      [点我收藏+]

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个字符串的读法。参考:GrandyangJustDoIT的博客。

思路:算法就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的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 计数和说

原文:http://www.cnblogs.com/love-yh/p/7054922.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!