题目描述(这题题目有点绕,多看几遍,如果还是不明白可以去leetcode网站看评论)
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
方法一:从i=1迭代迭代到i=n,但是时间复杂度很高,为O(n^3)。因此只打败了10%的答案。
class Solution
{
public:
string countAndSay(int n)
{
string s="1";
for (int i = 1; i < n; i++)
{
string temp;
for (int j = 0; j < s.size(); j++)
{
int count = 1;
while ((j+1) < s.size() && s[j] == s[j + 1])
{
count++;
j++;
}
temp = temp+to_string(count) + s[j];
}
s = temp;
}
return s;
}
};
int main()
{
Solution list;
int num;
cin >> num;
string str=list.countAndSay(num);
cout << str; //include<string> 可以直接用cout输出
}
方法二:使用递归。执行用时击败了90%的用户。
class Solution
{
public:
string countAndSay(int n)
{
if (n == 1) return "1";
string str = countAndSay(n - 1);
int count = 1;
string result;
for (int i = 0; i <str.size(); i++)//为什么不是i<str.size()-1
{
if (str[i] == str[i + 1])
{
count++;
}
else
{
result += to_string(count) + str[i];
count = 1;
}
}
return result;
}
};
关于上面那个条件判断,一开始以为当i=str.size()-1时,str[i+1]会越界,但string类型最后一个默认是‘\0’, 所以str最后一个char和'\0'相比肯定不等,会执行else部分。而且如果写成i<str.size()-1, 运行时候会报错,原因是当递归到n=1,返回"1",执行countAndSay(2),这时str="1", 由于str.size()-1为0,将无法执行for()循环。