- 外观数列
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
countAndSay(1) = “1”
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
前五项如下:
-
1
-
11
-
21
-
1211
-
111221
第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 “11”
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 “21”
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 “1211”
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 “111221”
class Solution {
public:
string countAndSay(int n) {
if(n == 1) {
return "1";
}
if(n >= 2) {
string outPut = countAndSay(n - 1);
string outPutStr;
int index = 0;
while(index < outPut.size()) {
int curCount = 1;
char curChar = outPut[index];
while(index < outPut.size() && outPut[index] == curChar) {
curCount++;
index++;
}
curCount--;
outPutStr += to_string(curCount) + curChar;
}
cout<<"now show the n:"<<n<<", tempOutputStr:"<<outPutStr<<endl;
return outPutStr;
}
return "";
}
};
非递归法实现
class Solution {
public:
string countAndSay(int n) {
string s1 = "1";
for(int i = 1; i < n ; i++) {
string outStr;
int curCount = 0;
char curChar = s1[0];
for(int j = 0; j < s1.length(); j++) {
if(s1[j] == curChar) {
curCount++;
} else {
outStr += to_string(curCount) + curChar;
curCount = 1;
curChar = s1[j];
}
}
outStr += to_string(curCount) + curChar;
s1 = outStr;
cout<<"now show n :"<<n<<", now show outStr:"<<outStr<<endl;
}
return s1;
}
};