leetcode [#38] | GCidea's blog
目录

题目
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.Note:
The sequence of integers will be represented as a string.
解决方案
1 | public class Solution { |
注意事项
- 本题重在找到数字序列的变化规律。第n代的结果一定是偶数个元素,因为每个数字都会被表示成“几个几”的形式。结果序列是由一系列1,2,3构成的。
- 状态转移图如下:
1 -> 11
2 -> 12
3 -> 13
11 -> 21
12 -> 1112
13 -> 1113
22 -> 22
33 -> 23
111 -> 31
222 -> 32
333 -> 33 - 根据上述状态转移图,遍历每次生成的字符串(此处是StringBuilder),决定下一次输出的是什么。