The Count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as "one 1" or 11 .
11is read off as "two 1s" or 21 .
21is 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.
Idea: The simulation process is OK. One thing learned here is that the STL has an int to string function called to_string (). Used to be used StringStream to turn ...
1 classSolution {2 Public:3 stringCountandsay (intN) {4 if(N <1)return "";5 stringres ="1";6 for(inti =2; I <= N; i++)7 {8 stringtem;9 CharCur = res[0];Ten intCount =1; One for(intj =1, n = res.size (); J < N; J + +) A { - if(cur = = res[j]) count++; - Else the { -Tem.append (to_string (count) +cur); -Cur =Res[j]; -Count =1; + } - } +Tem.append (to_string (count) +cur); Ares =tem; at } - returnRes; - } -};
Amazon polygon questions have an array length encoding, similar to this one, except for an int array, the returned result is an int array, and only needs to be encoded once.
1 classSolution2 {3 Public:4vector<int> arraylengthencoding (vector<int>&bits)5 {6vector<int>Res;7 if(!bits.size ())returnRes;8 intCur = bits[0], Count =1;9 for(inti =1, n = bits.size (); I < n; i++)Ten { One if(Bits[i] = = cur) count++; A Else - { - res.push_back (cur); the Res.push_back (count); -Cur =Bits[i]; -Count =1; - } + } - //we need to add the last part of Bits + res.push_back (cur); A Res.push_back (count); at returnRes; - } -};
Count and Say (Array Length Encoding)--Leetcode