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.
此题看了半天没看懂,后来 http://www.careercup.com/question?id=4425679大概明白题意
弄清题意在做,否则离题千里!!
意思是输入数字n,输出第n 个序列。第一个序列为 1 ,第二个由第一个产生11(1个1),下一个为21(2个1),下一个为1211(1个2,1个1)。。依次下去。明白题意后就不是很难了。迭代生成。
string countAndSay(int n)
{
if(n <= 0) return string();
string start_str = "1";
if(n == 1) return start_str;
while( n > 1)
{
start_str = get_next_str(start_str); //每次获取下一个
--n;
}
return start_str;
}
//字符串用string处理,如此处理不是很好,但是大小有不清楚。
string get_next_str(string &str)//此函数相当于字符串压缩
{
int count = 1;//开始想用char型直接加1操作,后来一想,万一溢出很难查
int pos = 0;
string res;
while(str[pos] != '\0')
{
if(str[pos] != str[pos+1])
{
string count_str;
stringstream str_stream;
str_stream<<count;
str_stream>>count_str;
res = res+count_str+str[pos];
count = 1;
}
else
{
count ++;
}
pos++;
}
return res;
}