题目描述:
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
前五项如下:
要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
示例 1:
class Solution {
public String countAndSay(int n) {
// 递归终止条件
if (n == 1) {
return "1";
}
StringBuffer res = new StringBuffer();
// 拿到上一层的字符串
String str = countAndSay(n - 1);
int length = str.length();
// 开始指针为0
int start = 0;
// 注意这从起始条件要和下面长度统一
for (int i = 1; i < length + 1; i++) {
// 字符串最后一位直接拼接
if (i == length) {
res.append(i - start).append(str.charAt(start));
// 直到start位的字符串和i位的字符串不同,拼接并更新start位
} else if (str.charAt(i) != str.charAt(start) ) {
res.append(i - start).append(str.charAt(start));
start = i;
}
}
return res.toString();
}
}