The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1Is read off"one 1"Or11.
11Is read off"two 1s"Or21.
21Is read off"one 2, Thenone 1"Or1211.
Given an integerN, GenerateNTh sequence.
Note: The sequence of integers will be represented as a string.
Train of Thought: the number of times each character in a string is counted, and the next one needs to be obtained based on the previous one. Therefore, two strings are required.
The maximum value of time is 3, because if two different values are combined, for example, 12 -- "1112, and two identical values are 11 --" 21.
Class solution {public: Char myitoa (int A) {return a + '0';} string countandsay (int n) {string S = "1"; string res; int time = 1; if (n = 1) return s; while (n-1) {-- N; Res. clear (); int Len = S. size (); For (INT I = 0; I <Len; ++ I) {if (I! = Len-1 & S [I] = s [I + 1]) + + time; else {res. push_back (myitoa (time); // time is a number and Res. push_back (s [I]); time = 1 ;}} S. clear (); s = res;} return res ;}};
Count and say