题目描述
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
countAndSay(1) = “1”
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
前五项如下:
-
1
-
11
-
21
-
1211
-
111221
第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 “11”
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 “21”
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 “1211”
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 “111221”
要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
思路
从上往下 找规律
第一行 为 1
第二行为 11
需要计数 + 循环 相结合
一个指针 i 用于 循环 character
另一个指针 count 用来 计数 当前character的数量
重点在于 计数 完成之后,即
将 count添加,字符添加,
然后 字符跳转到 count的位置,
然后count 从1 从新开始计数
代码
class Solution {
public String countAndSay(int n) {
String s = "1";
for (int i = 1; i < n; i++){
StringBuilder sb = new StringBuilder();
char start = s.charAt(0);
int count = 0;
for (int j = 0; j < s.length(); j++){
char c = s.charAt(j);
if (c == start){
count++;
} else{
sb.append(count).append(start);
count = 1;
start = s.charAt(j);
}
}
sb.append(count).append(start);
s = sb.toString();
}
return s;
}
}
class Solution {
public String countAndSay(int n) {
String s = "1";
if (n == 1){
return s;
}
int index = 0;
int countp = 0;
String s2 = "";
while (n > 1){
while (countp < s.length()){
while(s.charAt(index) == s.charAt(countp)){ // increase the num of countp, untill it's nolonger on the same character as the index pointer
countp++;
}
s2 += String.valueOf(countp - index); // counting the num of character in the row
s2 += s.charAt(index);
// reset the index to where the countp is
index = countp;
}
s = s2;
s2 = "";
index = 0; // put pointers back at the first index
countp = 0;
n--;
}
return s;
}
}
Reference
https://leetcode.cn/problems/count-and-say