第n个字符串依赖于第n-1个字符串,从左往右依次数出有连续几个数字。举例如下:
1
11 上个字符串中有1个1
21 上个字符串中有2个1
1211上个字符串中有1个2、1个1
111221
312211上个字符串中有3个1、2个2、1个1
13112221
1113213211
实现代码如下:
class Solution {
public:
string countAndSay(int n) {
string s="1";
for(int i=1;i<n;i++)
{
string temp="";
int count=1;
for(int j=0;j<s.size();j++)
{
while(j<s.size()-1&&s[j]==s[j+1])
{
count++;
j++;
}
temp=temp+(char)(count+'0')+s[j];
count=1;
}
s=temp;
}
return s;
}
};