题目: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(n),就是根据string(n-1)进行求解,所以使用了迭代的方法。
真正开始判断的时候,定义一个count和一个初始的位置,这种方法已经不止一次的遇到!!!
只要是相同,那么就下一个,并且count加1,如果不同先是插入几个不同的数字,再插入原来的字符。
但是要注意最后的一个字符。
还有一个思路没有看。也贴上来。
代码:
class Solution {
public:
//https://leetcode.com/problems/count-and-say/
string countAndSay(int n) {
//return solution1(n); //recursive
return solution2(n); //iterative
}
private:
string solution1(int n){
if(n == 2) return "11";
if(n == 1) return "1";
string s = solution1(n - 1);
int count = 1, i;
char c = s[0];
string ns;
for(i = 1; i < s.length(); i++){
if(s[i] == c) count++;
else{
ns += char('0'+count);
ns += c;
c = s[i];
count = 1;
}
}
if(i == s.length()){
ns += char('0'+count);
ns += c;
}
return ns;
}
string solution2(int n){
if(n-- == 1) return "1";
string cur, pre = "11";
while(--n){
int count = 1, i;
char c = pre[0];
for(i = 1; i < pre.length(); i++){
if(pre[i] == c) count++;
else{
cur += char('0'+count);
cur += c;
c = pre[i];
count = 1;
}
}
if(i == pre.length()){
cur += char('0'+count);
cur += c;
}
pre = cur;
cur = "";
}
return pre;
}
};