题目
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 1
- 11
- 21
- 1211
- 111221
1
is read off as"one 1"
or11
.11
is read off as"two 1s"
or21
.21
is read off as"one 2
, thenone 1"
or1211
.
Given an integer n where 1 ≤ n ≤ 30, generate the n th term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
分析
给一个整型变量n,根据规律计算第n层的字符串值,编程思路:
从第1层的“1”开始计算,用两层循环实现,外层循环实现层数i的递增,内层循环实现分析计算 i-1 层。
Java实现代码:
public class countAndSay{
public static String test(int n) {
StringBuilder curr = new StringBuilder("1");
StringBuilder prev;
int count;
char say;
for(int i=1;i<n;i++) {
prev = curr;
curr = new StringBuilder();
count = 1;
say = prev.charAt(0); //say获取prev 0 位置字符
for(int j=1;j<prev.length();j++) {
if(prev.charAt(j) != say) {
//如果j位置的字符与say字符不一致,输出count和say并重置两个变量值进行新一轮计算
curr.append(count).append(say);
count = 1;
say = prev.charAt(j);
}
else count++;//一致
}
//更新curr当前层(i层)的字符串值
curr.append(count).append(say);
}
return curr.toString();
}
}