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.
One is read off as "1s" or 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 would be represented as a string.
Idea: A number a continuously appeared n times, read into "NA",
The implementation is as follows:
classSolution { Public:stringTOSTR (intc) {stringRetStringStreamss ss<<c; Ret=ss.str ();cout<<ret<<endl;returnRet }stringCTOSTR (Charc) {stringRetStringStreamss ss<<c; Ret=ss.str ();returnRet }stringCountandsay (intN) {strings="1"; for(intI=2; i<=n;i++) {Charlast=' A ';intCnt=0;stringR=""; for(intj=0; J<s.length (); j + +) {if(last==' A ') {Last=s[j]; Cnt=1; }Else if(Last==s[j]) {cnt++; }Else{R+=TOSTR (CNT); R+=ctostr (last); Cnt=1; LAST=S[J]; }} r+=tostr (CNT); R+=ctostr (last); S=r; }returnS }};
Count and Say