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.
Read the other people's explanations on the internet to understand
1 read into a 1 11
11 read two X 1 21
21 read into a 21 1 1211
1211 read it into a 11 22 x 1 111221
Code implementation
PublicString Countandsay (intN) {intI=1; String result= "1"; while(i<N) {result=countandsaystring (Result); I++; } returnresult; } Publicstring countandsaystring (String str) {if(Str.equals ("1")) return"11"; CharCur=str.charat (0);//Current number intCount=1;//Current number of numbersStringBuilder stringbuilder=NewStringBuilder (); for(intI=1;i<str.length (); i++) { if(cur==Str.charat (i)) {Count++; if(I==str.length ()-1) {stringbuilder.append (count). append (cur); } } Else{stringbuilder.append (count). append (cur); Cur=Str.charat (i); Count=1; if(I==str.length ()-1) {stringbuilder.append (count). append (cur); } } } returnstringbuilder.tostring (); }
Leetcode Count and Say