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.
Solution:下一个字符串= 当前字符串:∑(字符个数+字符),例如1211,下一个字符串=count(1)+'1'+count(2)+'2'+count(1)+'1'=111221
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 string ret="1"; 5 if(n==1)return ret; 6 while(--n){ 7 string next; 8 char last=ret[0]; 9 int i=1,count=1; 10 while(i<ret.size()) 11 { 12 while(ret[i]==last&&i<ret.size()){ 13 i++; 14 count++; 15 } 16 if(i<ret.size()&&ret[i]!=last){ 17 next+=to_string(count); 18 next+=last; 19 20 count=1; 21 last=ret[i]; 22 i++; 23 } 24 } 25 next+=to_string(count); 26 next+=last; 27 ret=next; 28 } 29 return ret; 30 } 31 };