The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1
is read off as "one 1"
or 11
.11
is read off as "two 1s"
or 21
.21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1" Explanation: This is the base case.Example 2:
Input: 4 Output: "1211" Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1
and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
外观数列。题意是根据规律输出数字。规律如下,
- 首先1,自然表示为1,而say出来就是1个1
- 所以2应该表示为11,而say出来就是2个1
- 所以3应该表示为21,而say出来就是1个2,1个1
- 所以4应该表示为1211,以此类推
- 5 - 111221
- 6 - 312211
这个题没有什么好的思路,就只能按照规则一个个算下一个数是多少,直到第N个数字。首先第一个数字一定是1,所以可以先用一个变量res记录下来,然后之后的数字都依据遍历第一个数字的结果来记录。直接看代码应该可以懂。
时间O(1) - 因为时间复杂度并不完全根据input大小有线性关系
空间O(n)
Java实现
1 class Solution { 2 public String countAndSay(int n) { 3 int i = 1; 4 String res = "1"; 5 while (i < n) { 6 int count = 0; 7 StringBuilder sb = new StringBuilder(); 8 char c = res.charAt(0); 9 for (int j = 0; j <= res.length(); j++) { 10 if (j != res.length() && res.charAt(j) == c) { 11 count++; 12 } else { 13 sb.append(count); 14 sb.append(c); 15 if (j != res.length()) { 16 count = 1; 17 c = res.charAt(j); 18 } 19 } 20 } 21 res = sb.toString(); 22 i++; 23 } 24 return res; 25 } 26 }
JavaScript实现
1 /** 2 * @param {number} n 3 * @return {string} 4 */ 5 var countAndSay = function (n) { 6 let i = 1; 7 let res = '1'; 8 while (i < n) { 9 let count = 0; 10 let sb = []; 11 let c = res.charAt(0); 12 for (let j = 0; j <= res.length; j++) { 13 if (j != res.length && res.charAt(j) === c) { 14 count++; 15 } else { 16 sb.push(count); 17 sb.push(c); 18 if (j != res.length) { 19 count = 1; 20 c = res.charAt(j); 21 } 22 } 23 } 24 res = sb.join(''); 25 i++; 26 } 27 return res; 28 };