[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个字符串的读法。参考: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();++j)
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 };

转载于:https://www.cnblogs.com/love-yh/p/7054922.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值