【Leetcode】【Easy】Count and Say

本文详细介绍了如何通过迭代方法生成计数说数序列的第n项,包括C++代码实现及注意事项。重点讨论了字符串操作、字符与数字之间的转换,以及如何避免程序在特定条件下的失败。

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.

 

解题思路:

第一个string为1,从第二个string开始,对前一个string的每一位进行操作,一位一位遍历,前后位相同,则记录当前数字数量,遇到前后不同,则对新的string进行写入。循环n-1次。

注意:

1、C++中string类型的正确操作;

2、C++中string和char*的区别和转换;

3、数字和字符Ascii码的转换方法;

特别注意:

代码中使用 n(int) + '0' 来表示'n',当且仅当n(int)<10时有效,因此如果sameDigCount超过10,也就是连续出现10个相同数字时,程序失败。不过可以轻松证明(证明略),连续出现的数字最多3个,也就是string串中最大的数字是3,不会超过4。因此代码是没有问题的。

 

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string currentStr = "1";
 5         
 6         if (n<=0) 
 7             return "";
 8         
 9         while (--n) {
10             string nextStr = "";
11             int sameDigCount = 1;
12             int strlen = currentStr.length();
13             char preDigital = currentStr[0];
14             
15             for (int i=1; i<strlen; ++i) {
16                 if (currentStr[i] == preDigital) {
17                     ++sameDigCount;
18                 } else {
19                     nextStr.push_back(sameDigCount+'0');
20                     nextStr.push_back(preDigital);
21                     preDigital = currentStr[i];
22                     sameDigCount = 1;
23                 }
24             }
25                 
26             nextStr.push_back(sameDigCount+'0');
27             nextStr.push_back(preDigital);
28             currentStr = nextStr;
29         }
30         
31         return currentStr;
32     }
33 };

 

附录:

C++ string 操作总结

转载于:https://www.cnblogs.com/huxiao-tee/p/4109596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值