[Link] https://leetcode.com/problems/count-and-say/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public String countAndSay(int n) {
StringBuilder sb = new StringBuilder();
sb.append(1);
rec(sb, 1, n);
return sb.toString();
}
public void rec(StringBuilder sb, int idx, int n) {
if(idx == n) return;
String s = sb.toString();
sb.setLength(0);
int i = 0, j = 0, cnt = 0, len = s.length();
while(i < len) {
char c = s.charAt(i);
j = i;
cnt = 1;
while(j + 1 < len && s.charAt(j + 1) == c) {
j++;
cnt++;
}
sb.append(cnt).append(c);
i += cnt;
}
rec(sb, idx + 1, n);
}
}