导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-38.Count and Say

题目

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 n th sequence.

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

翻译

数和说序列是一个由以下数字开始的序列: 1, 11, 21, 1211, 111221, …
1 读作 “一个1“ ,或者 11
11 读作 “两个1“ ,或者 21
21 读作 “一个2,然后一个1“ ,或者 1211
给出一个整数 n ,生成第 n 个序列。
注意:数字序列应当被表示为一个字符串。

从1到n,逐个计算。
对于从n-1到n,先记录第一个数字,向后循环直到遇到不同数字,将个数和数字输出,更新记录的数字和个数,扫描到结尾即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public String countAndSay(int n) {
String say = "1";
for (int i = 1; i < n; i++) {
char lastChar = say.charAt(0);
int count = 1;
StringBuilder saysb = new StringBuilder();
for (int j = 1; j < say.length(); j++) {
char cur = say.charAt(j);
if (lastChar == cur) count++;
else {
saysb.append(count).append(lastChar);
lastChar = cur;
count = 1;
}
}
saysb.append(count).append(lastChar);
say = saysb.toString();
}
return say;
}
}