持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天。
1. 题目介绍(count-and-say)
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
【Translate】: count-and-say序列是由递归公式定义的数字字符串序列
- 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.
【Translate】:
- countAndSay(1) = "1"
- countAndSay(n)是您将“说”来自countAndSay(n-1)的数字字符串的方式,然后将其转换为不同的数字字符串。
To determine how you "say" a digit string, split it into the minima l 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.
【Translate】: 要确定如何“说”一个数字字符串,请将其分成最小数量的组,以便每组都是具有相同字符的连续部分。然后,说出每组字的数量,然后说出字。要将该语句转换为数字字符串,请将计数替换为一个数字,并将每个语句连接起来。
For example, the saying and conversion for digit string "3322251":
【Translate】: 例如,对数字字符串“3322251”的说和转换
Given a positive integer n, return the nth term of the count-and-say sequence.
【Translate】: 给定一个正整数n,返回 count-and-say序列的第n项。
【测试用例】:
【约束】:
2. 题解
2.1 递归拼接
ayyild1z 提供的题解 Clean Short Java Solution,通过递归来拼接获得完整的字符串。
// for the nth number, you just need to count characters of the (n-1)th number,
// for the (n-1)th number, you just need to count characters of the (n-2)th number,
// ...
public String countAndSay(int n) {
if(n == 1) return "1";
StringBuilder res = new StringBuilder();
// recursively call for (n-1) th number, "0" is only for the edge case at the end of the loop with `s.charAt(i+1)`
String s = countAndSay(n-1) + "0";
for(int i=0, c=1; i < s.length()-1; i++, c++){
// if next digit is different, then append the count so far `c` and the digit itself, then set count `c` to zero
if(s.charAt(i+1) != s.charAt(i)){
res.append(c).append(s.charAt(i));
c = 0; // 计数清零
}
}
return res.toString();
}
2.2 循环拼接字符串
zhibzhang 提供的题解 Straightforward Java Solution。从1开始,一步步完成字符串的拼接,直到n。
public String countAndSay(int n) {
String s = "1";
for(int i = 1; i < n; i++){
s = countIdx(s);
}
return s;
}
public String countIdx(String s){
StringBuilder sb = new StringBuilder();
char c = s.charAt(0); // 取第一个元素做比较,而不是使用i和i+1比较,可以有效防止数组越界
int count = 1;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == c){
count++;
}
else
{
sb.append(count);
sb.append(c);
c = s.charAt(i); // 更换下一个比较对象
count = 1;
}
}
sb.append(count);
sb.append(c);
return sb.toString();
}