您的位置:首页 > 其它

【Leetcode】【Easy】Count and Say

2014-11-20 00:38 267 查看
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。因此代码是没有问题的。

class Solution {
public:
string countAndSay(int n) {
string currentStr = "1";

if (n<=0)
return "";

while (--n) {
string nextStr = "";
int sameDigCount = 1;
int strlen = currentStr.length();
char preDigital = currentStr[0];

for (int i=1; i<strlen; ++i) {
if (currentStr[i] == preDigital) {
++sameDigCount;
} else {
nextStr.push_back(sameDigCount+'0');
nextStr.push_back(preDigital);
preDigital = currentStr[i];
sameDigCount = 1;
}
}

nextStr.push_back(sameDigCount+'0');
nextStr.push_back(preDigital);
currentStr = nextStr;
}

return currentStr;
}
};


附录:

C++ string 操作总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: