38. 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
class Solution {
public String countAndSay(int n) {
String str = "1";
for (int i = 2; i <= n; i++) {
StringBuilder sb = new StringBuilder();

int j = 0;
char c = str.charAt(j);
for (int k = j + 1; k < str.length(); k++) {
if (str.charAt(k) != c) {
sb.append(k - j).append(c);
c = str.charAt(k);
j = k;
}
}

sb.append(str.length() - j).append(c);
str = sb.toString();
}

return str;
}
}

References

38. Count and Say