題目要求:
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1
is read off as "one
1"
or 11
.11
is read off as "two
1s"
or 21
.21
is read off as "one
2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
------------------------------------------------------------------------------------------------------------------n=1 返回1
n=2由於n=1的結果爲1,有1個1,所以返回11
n=3由於n=2結果爲11,有2個1,返回21
n=4由於n=3結果爲21,有1個2和1個1,所以返回1211
給定n,以此類推
解答:遍歷每個子串,根據統計個數(如1115,計算爲3115)衍生出新的子串,循環遍歷,返回最後一次的結果代碼如下:
class Solution {
public:
string countAndSay(int n) {
string tmp;
string result;
char c = 1 + '0';
result += c;
tmp += c;
int i = 1;
while(i < n)
{
string tmp1;
int k = 1;
for(int j = 0 ;j < tmp.length(); j++)
{
if(j+1 == tmp.length())
{
tmp1 += char(k+'0');
tmp1 += tmp[j];
break;
}
//統計每個數字的個數
if(tmp[j] == tmp[j+1])
{
k++;
continue;
}
else
{
tmp1 += char(k+'0');
tmp1 += tmp[j];
k = 1;
}
}
if(tmp1.length() == 0)
{
tmp1 += char(k+'0');
tmp1 += tmp[0];
}
i++;
tmp = tmp1;
result = tmp1;
}
return result;
}
};