LeetCode 38. Count and Say (Count and speak) solutions and methods

Source: Internet
Author: User

LeetCode 38. Count and Say (Count and speak) solutions and methods
Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21,121 1, 111221 ,...

1 is read off as one 1 or 11.
11 is read off as two 1 s or 21.
21 is read off as one 2, then one 1 or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

 

Idea: It is too difficult to understand the meaning of the question, especially in English. You can only refer to other people's documents and understand the rules. Finally, I understand that when n = 1, the output string 1; when n = 2, the number of values in the previous string is counted. Because the previous string has 1, the output is 11; when n = 3, because the last character is 11, there are 2 1, so the output is 21; when n = 4, because the last string is 21, there are 1 2 and 1, therefore, the output is 1211. Similarly, write a countAndSay (n) function to return a string.

The meaning is easy to understand. It is a typical recursive problem. Its code is very simple, as follows:

 

Public class Solution {public String countAndSay (int n) {if (n = 1) {return 1;} // recursive call, and then process String str = countAndSay (n-1) + *; // For the mark at the end of str, it is convenient to read char [] c = str cyclically. toCharArray (); int count = 1; String s =; for (int I = 0; I <c. length-1; I ++) {if (c [I] = c [I + 1]) {count ++; // count increase} else {s = s + count + c [I]; // The * mark above facilitates unified processing of count = 1; // initialization} return s ;}}


 

 

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.