外观数列
给定一个正整数 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” 要 描述 一个数字字符串,首先要将字符串分割为 最小
数量的组,每个组都由连续的最多 相同字符
组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
#include <iostream>
#include <sstream>
using namespace std;
class Solution {
public:
// 双指针法
string countAndSay(int n)
{
string pre = "";
string cur = "1";
for (int i = 1; i < n; i++)
{
pre = cur;
cur = "";
int start = 0, end = 0;
while (end < pre.size())
{
while (end < pre.size() && pre[start] == pre[end])
{
end++;
}
// 字符串流 拼接
ostringstream ostr;
ostr << end - start << pre[start];
cur += ostr.str();
start = end;
}
}
return cur;
}
};
int main() {
int n;
cin >> n;
Solution* s = new Solution();
cout << s->countAndSay(n);
delete s;
cout << "==================" << endl;
string table = "1";
for (int i = 1; i < n; i++)
{
string res = "";
int count = 0;
string str = table;
char temp;
for (int j = 0; j < str.size(); j++)
{
if (j == 0)
{
temp = str[j];
count++;
}
else if (str[j] == temp)
{
count++;
}
else
{
ostringstream sout;
sout << count << temp;
res += sout.str();
count = 1;
temp = str[j];
}
if (j + 1 == str.size())
{
ostringstream sout;
sout << count << temp;
res += sout.str();
}
}
table = res ;
}
cout << table;
return 0;
}