version at: 2022-03-29
/**
1. 按题面意思, 递归的找, 因为先要知道上一个串是什么才能读出来
2. 读string 就查相邻的字符个数合并成几个几的形式
*/
class Solution {
public String countAndSay(int n) {
if (n == 1) return "1";
String prev = countAndSay(n-1);
StringBuffer buffer = new StringBuffer();
for (int i = 0, count = 0; i< prev.length(); i++) {
char cur = prev.charAt(i);
char next = i + 1 < prev.length() ? prev.charAt(i+1) : ' ';
if (cur == next) {
count++;
} else {
buffer.append(String.valueOf(count+1));
buffer.append(String.valueOf(cur));
count = 0;
}
}
return buffer.toString();
}
}
version at: 2022-02-10
// 1. 按题意双指针查找即可,就是题意有些难理解
class Solution {
public String countAndSay(int n) {
String s = "1";
StringBuilder buffer = new StringBuilder();
for (int i = 2 ; i <= n ; i ++){
buffer.setLength(0);
for (int j = 0, k = 0; j < s.length(); j = k){
while ( k < s.length() && s.charAt(k) == s.charAt(j)) k++;
buffer.append(String.valueOf(k-j));
buffer.append(s.charAt(j));
}
s = buffer.toString();
}
return s;
}
}