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 "one 2
as, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note:the sequence of integers would be represented as a string.
Solution: Next string = Current string: ∑ (number of characters + characters), such as 1211, next string =count (1) + ' 1 ' +count (2) + ' 2 ' +count (1) + ' 1 ', =111221
1 classSolution {2 Public:3 stringCountandsay (intN) {4 stringret="1";5 if(n==1)returnret;6 while(--N) {7 stringNext;8 Charlast=ret[0];9 intI=1, count=1;Ten while(i<ret.size ()) One { A while(ret[i]==last&&i<ret.size ()) { -i++; -count++; the } - if(I<ret.size () &&ret[i]!=Last ) { -next+=to_string (count); -next+=Last ; + -Count=1; +last=Ret[i]; Ai++; at } - } -next+=to_string (count); -next+=Last ; -ret=Next; - } in returnret; - } to};
"Leetcode" 38-count and Say