The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
思路很简单,从1开始一个一个数数到n。数1的时候,产生一个StringBuilder用来维护第一个的读音,也就是“11”。然后把“11“作为输入继续数,可用递归, 每递归一层加1.
public String countAndSay(int n) {
String num = "1";
int countAll = 1;
return countAndSay(num, countAll, n);
}
private String countAndSay(String num, int countAll, int n) {
if (countAll >= n) {
return num;
}
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 0; i < num.length() - 1; i++) {
if (num.charAt(i) == num.charAt(i + 1)) {
count++;
} else {
sb.append(count);
sb.append(num.charAt(i));
count = 1;
}
}
sb.append(count);//最后跳出循环要考虑append上最后一串的count and say
sb.append(num.charAt(num.length() - 1));
num = sb.toString();
return countAndSay(num, countAll+1, n);
}