这个还是一开始没读懂题目,题目如下:
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"
or11
.
11
is read off as"two 1s"
or21
.
21
is read off as"one 2
, thenone 1"
or1211
.Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
这样的规律依次向下,第一个是"1",然后第二个"11"代表一个1,依次递推,然后给一个数,然后返回在这个规律下的第n个数。【我之前看成了返回这种表达方式的n】【泪目】
因为考虑了递归的低效性,所以我打算用迭代来做,噢,对了,顺便说个坑,我在把int转string的时候用到了itoa这个工具函数,然后VS告诉我itoa不是安全函数请使用_itoa,在我改了后又给我弹出error说_itoa也不是安全的了,请使用_itoa_s,当我在VS中调试正常后,结果发现leetcode的OJ不支持_itoa_s。。。。。
所以我就手写了一个itoa,虽然不算太高效,但是还是能用的。这个题目的题解如下:
class Solution {
public:
string itoa_better(int n)
{
string tmp = "";
while (n != 0)
{
tmp += (n % 10 + '0');
n = n / 10;
}
reverse(tmp.begin(), tmp.end());
return tmp;
} string Say(string n)
{
char word[1] = { n[0] };
int sum = 1;
string Say = "";
string Sum = ""; for (string::iterator i = n.begin() + 1; i != n.end(); i++)
{
if (*i != word[0])
{
Say += itoa_better(sum) + word[0];
sum = 0;
word[0] = *i;
}
sum += 1;
}
Say += itoa_better(sum) + word[0]; return Say;
} string countAndSay(int n)
{
string tmp = "1"; for (int i = 0; i < n - 1; i++)
{
tmp = Say(tmp);
} return tmp;
}
};