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.
Difficulty: Easy
简单的字符串处理
string countAndSay(int n) {
if(n==1)
return "1";
string s;
s = "1";
int i = 1;
while(i<n)
{
string ans;
int len = s.length();
char curr,cou = '0';
ans.clear();//清空ans
for(int j = 0;j<len;j++)
{
if(len==1)
{
ans = "11";
continue;
}
if(j==0){
curr = s[j];
cou = '1';
}
if(curr != s[j]&&j!=len-1&&j!=0)
{
ans = ans + cou + curr;
curr = s[j];
cou = '1';
}
else if(curr == s[j]&&j!=0&&j!=len-1)
{
cou = cou+1;
}
else if(j==len-1&&curr == s[j])
{
cou = cou+1;
ans = ans + cou + curr;
}
else if(j==len-1&&curr != s[j])
{
ans = ans + cou + curr;
cou = '1';
ans = ans + cou +s[j];
}
}
i++;
s = ans;
}
return s;
}