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.
如果有更好更高效的代码,希望大家共享~
class Solution {
public:
string countAndSay(int n) {
string seq = "1";
string result = "";
int count = 1;
char pre;
if(n > 1)
{
for (int i = 2; i <= n; i++)
{
pre = ' ';
for (int j = 0; j < seq.size(); j++)
{
if(j + 1 < seq.size() && seq[j + 1] == seq[j])
{
count++;
}
else
{
pre = seq[j];
result.push_back(count + '0');
result.push_back(pre);
count = 1;
}
}
seq = result;
result = "";
}
return seq;
}
else if(n == 1)
{
return "1";
}
}
};
本文不详尽或错误之处,请各位不吝言辞,多多指教~谢谢~
作者:Louise http://blog.csdn.net/yupingliu