LeetCode 38. 报数
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
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 项。
注意:整数顺序将表示为一个字符串。
法一:递归(程序相对简单,但是内存占用空间大,空间复杂度增加)
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1";
string fstr=countAndSay(n-1);
string str;
int j;
for(int i=0;i<fstr.length();i=j){
for(j=i+1;j<fstr.length();j++){
if(fstr[j]!=fstr[i]) break;
}
str.push_back('0'+j-i);
str.push_back(fstr[i]);
}
return str;
}
};
执行用时 : 4 ms, 在Count and Say的C++提交中击败了98.58% 的用户
内存消耗 : 9.1 MB, 在Count and Say的C++提交中击败了33.07% 的用户
法二:循环遍历
class Solution {
public:
string countAndSay(int n) {
int k,j;
string str="1";
for(int i=1;i<n;i++){
k=0;
string tmp;
for(j=0;j<str.length();j++){
if(str[j]!=str[j-k]){
tmp.push_back('0'+k);
tmp.push_back(str[j-1]);
k=1;
}
else
k++;
}
tmp.push_back('0'+k);
tmp.push_back(str[j-1]);
str=tmp;
}
return str;
}
};
执行用时 : 4 ms, 在Count and Say的C++提交中击败了98.58% 的用户
内存消耗 : 8.8 MB, 在Count and Say的C++提交中击败了70.93% 的用户