Leetcode:Count and Say

本文介绍了一种通过模拟方式生成计数与描述序列的方法。该序列从1开始,每一步通过对当前序列进行读取并描述产生新的序列。文中提供了两种实现思路的代码示例,一种使用额外的字符简化了过程。

Description:

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开始,根据读音来产生新的序列,计算第n个字符串是什么。这里主要是一点:在写代码的时候

觉得有重复的部分,臃肿了一些,然后再室友的指导下,加了一个标示字符使代码更简洁。两个都贴上

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string nows = "1";
 5         stringstream itos;
 6         
 7         for(int i=2;i<=n;i++)
 8         {
 9             char nowc = nows[0];
10             int count =1;
11             string read,scount;
12             for(int j=1;j<nows.size();j++)
13             {
14                 if(nows[j]==nowc)
15                     count++;
16                 else{
17                     itos<<count;
18                     itos>>scount;
19                     itos.clear();
20                     read = read+scount+nowc;
21                     count = 1;
22                     nowc = nows[j];
23                 }
24             }
25             itos<<count;
26             itos>>scount;
27             itos.clear();
28             nows = read +scount +nowc;
29             
30         }
31         return nows;
32     }
33 };

 

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string nows = "1e";
 5         stringstream itos;
 6         
 7         for(int i=2;i<=n;i++)
 8         {
 9             char nowc = nows[0];
10             int count =1;
11             string read,scount;
12             for(int j=1;j<nows.size();j++)
13             {
14                 if(nows[j]==nowc)
15                     count++;
16                 else{
17                     itos<<count;
18                     itos>>scount;
19                     itos.clear();
20                     read = read+scount+nowc;
21                     count = 1;
22                     nowc = nows[j];
23                 }
24             }
25             nows = read +'e';
26             
27         }
28         string result(nows.begin(),nows.end()-1);
29         return result;
30     }
31 };

 

转载于:https://www.cnblogs.com/soyscut/p/3787564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值