[LeetCode] 38. Count and Say

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string "3322251":
Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:
Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Constraints:
1 <= n <= 30

外观数列。

给定一个正整数 n ,输出外观数列的第 n 项。 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。 你可以将其视作是由递归公式定义的数字字符串序列: countAndSay(1) = "1"countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。前五项如下: 1. 12. 113. 214. 12115. 111221第一项是数字 1 描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11" 述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。

例如,数字字符串 "3322251" 的描述如下图:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-and-say
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是按规则模拟/打表。
题目给的例子其实不太对,因为题目中规定了 n 最多到 30,例子给的 3322251 只是演示一下读这个数字的规则。

题目的定义是 countAndSay(n) 是对 countAndSay(n - 1) 的描述,所以我们可以从 1 开始一直遍历到 n,看看这个描述到底是什么。首先第一个数字一定是 1,所以可以先用一个变量 res 记录下来,然后之后的数字都依据遍历第一个数字的结果来记录。直接看代码应该可以懂。

复杂度

时间O(1) - 因为 N 的范围只到 30,所以只要算 30 次即可
空间O(n) - 用了一个stringbuilder记录中间结果

代码

Java实现

class Solution {
	public String countAndSay(int n) {
		String str = "1";
		for (int i = 2; i <= n; ++i) {
			StringBuilder sb = new StringBuilder();
			int start = 0;
			int pos = 0;
			while (pos < str.length()) {
				while (pos < str.length() && str.charAt(pos) == str.charAt(start)) {
					pos++;
				}
				sb.append(Integer.toString(pos - start)).append(str.charAt(start));
				start = pos;
			}
			str = sb.toString();
		}
		return str;
	}
}

相关题目

  1. Count and Say
  2. Encode and Decode Strings
  3. String Compression
  4. Design Compressed String Iterator
  5. Decompress Run-Length Encoded List
posted @ 2020-07-04 15:00  CNoodle  阅读(527)  评论(0编辑  收藏  举报