LintCode: Count and Say

C++代码实现数位计数与说数算法
本文详细介绍了使用C++语言实现数位计数与说数算法的过程,通过迭代处理字符串,计算并输出每个数字的连续出现次数及对应的数字,最后返回最终的计数字符串。

C++

 1 class Solution {
 2 public:
 3     /**
 4      * @param n the nth
 5      * @return the nth sequence
 6      */
 7     string countAndSay(int n) {
 8         // Write your code here
 9         if (0 == n) {
10             return "";
11         }
12         string pre = "1";
13         for (int i = 1; i < n; i++) {//从第2个(i=1)开始
14             char ch = pre[0];
15             string cur = "";
16             int cnt = 0;
17             for (int j = 0; j < pre.size(); j++) {
18                 if (pre[j] == ch) {
19                     cnt ++;
20                 } else {
21                     cur = cur + itostr(cnt) + ch;
22                     ch = pre[j];
23                     cnt = 1;
24                 }
25             }
26             if (cnt != 0) {//处理后边的字符
27                 cur = cur + itostr(cnt) + ch;
28             }
29             pre = cur;
30             cur = "";
31         }
32         return pre;
33         
34     }
35     string itostr(int i) {//自定义int转string函数
36         char str[10];
37         //itoa(str,i,10);->only support Windows
38         sprintf(str, "%d", i);//support any platforms
39         return str;
40     }
41 };

 

转载于:https://www.cnblogs.com/CheeseZH/p/5000386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值