难在了题目是什么意思呢?
初始值第一行是 1。
第二行读第一行,1 个 1,去掉个字,所以第二行就是 11。
第三行读第二行,2 个 1,去掉个字,所以第三行就是 21。
第四行读第三行,1 个 2,1 个 1,去掉所有个字,所以第四行就是 1211。
第五行读第四行,1 个 1,1 个 2,2 个 1,去掉所有个字,所以第五航就是 111221。
第六行读第五行,3 个 1,2 个 2,1 个 1,去掉所以个字,所以第六行就是 312211。
然后题目要求输入 1 - 30 的任意行数,输出该行是啥。
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
return "1";
else
{
string last = countAndSay(n - 1);
return getnextstr(last);
}
}
string getnextstr(string str)
{
string s="";
int nums = 0,j,cnt;
for (int i = 0; i < str.size(); i=j)
{
j = i;
cnt = 0;
while (j<str.size()&&str[j] == str[i])
{
cnt++;
j++;
}
stack<int> s1;
while (cnt)
{
s1.push(cnt % 10);
cnt /= 10;
}
char t;
while (s1.size())
{
t = s1.top() + '0';
s1.pop();
s = s + t;
}
s = s+ str[i];
}
return s;
}
};
扫描二维码关注公众号,回复:
8570253 查看本文章