Written question 51. Leetcode OJ (38)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.