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 ;}}