. Count and Say
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"
Or11
.
11
is read off as"two 1s"
Or21
.
21
is read off as"one 2
, thenone 1"
Or1211
.
Given an integer n, generate the nth sequence.
Note:the sequence of integers would be represented as a string.
According to the law can write the following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
Ideas:
1. Replace the storage record result,tmp with 2 strings.
2. record the current value n and get the maximum continuous length m of the current value.
Append "M" to the 3.tmp string and append "n".
Class solution {public: string countandsay (int n) { if (--n < 0) return ""; string result = "1"; string tmp; //temporary string int step = 1;//Step char cur; // Current element while (n) { cur = result[0]; for (Int i = 0; i < result.size (); i++) { if ( i+1 < result.size () &NBSP;&&&NBSP;RESULT[I]&NBSP;==&NBSP;RESULT[I&NBSP;+&NBSP;1]) { step++; } else { stringstream stepstreAm; stepstream << step; string stepstr = stepstream.str (); tmp.append (1,stepstr[0]); Tmp.append (1,cur); step = 1; cur = result[i + 1]; } } swap (result, TMP); tmp = ""; n--; } return result; }};
2016-08-10 17:24:26
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836606
Leetcode 38. Count and Say strings