"Leetcode Test Instructions Analysis & Solution" 38. Count and Say

Source: Internet
Author: User

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.

Test Instructions Analysis:

The subject is to start the number from 1, and convert the current number to spoken numbers. For example, 1 colloquial is a 1, recorded as 11;11 read 2 1, recorded as 21;21 read as a 2, a 1, recorded as 1211 ...

' 1 ' is the first number, based on the number n entered, calculates the nth number.

It's a bit of a mouthful, and you can feel it against an example ...

Answer:

If you understand test instructions, then the answer is simple. The direct loop, each number according to the topic request translates into the corresponding number, in order to find the nth return on the line.

Leetcode gives the rating is easy, which is difficult for the program, but for test instructions to understand the bias.

AC Code:

classsolution (object):defCountandsay (self, n):ifN < 2:return '1'Ret_str='1'         whilen > 1: Temp, Current_num="', 0 forI, VinchEnumerate (RET_STR):ifI > 0 andV! = ret_str[i-1]: Temp+ = str (current_num) + ret_str[i-1] Current_num= 1Else: Current_num+ = 1Ret_str= temp + (str (current_num) + ret_str[-1]ifCurrent_num! = 0Else "') n-= 1returnRet_str

Something:

In fact, this problem has a very interesting place, that is, the output of the number will never be greater than 3 of the number, will only appear 1, 2, 33 numbers, you can prove it?

"Leetcode Test Instructions Analysis & Solution" 38. Count and Say

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.