This question is a numerical law problem, the title means, given a value of N, according to the law to list the nth number, the law as shown in, the approximate meaning is that the number of the left is the next number, for example:
1. "1", which is represented by a 1, becomes "11"
2. "11", which consists of 2 1, becomes "21"
3. "21", which consists of a 2 and a 1, becomes "1211"
The rule is that this is the case, or it is relatively easy to understand. The code is as follows:
Class Solution {public:string Countandsay (int n) {//This question is a number game bar string ret= ""; if (n = = 0) {return ret; }//n = = 1 String tmp = "1"; if (1 = = N) {return tmp; }//n > 1 for (int i = 1; i < n; ++i) {ret.clear (); size_t j = 0; while (J < Tmp.size ()) {char ch = tmp[j]; Count the number of repetitions, such as ' 11 '-' + ' int num = 1; while (J+num < Tmp.size () && tmp[j + num] = = Tmp[j]) {++num; The IF (1 = = num) {//description does not have a repeating number because NUM starts with 1, then the tmp[j] is separate RET.P Ush_back (' 1 '); } else {//Otherwise the duplicate number is indicated, NUM is the number of repetitions ret.push_back (num + ' 0 '); } ret.push_back (Tmp[j]); j + = num; } TMP = RET; } return ret; }};
The results are as follows:
Written question 51. Leetcode OJ (38)