问题描述:
The count-and-say sequence is the sequence of integersbeginning as follows:
1, 11, 21,1211, 111221, ...
1
is read off as "one1"
or 11
.
11
is read off as "two1s"
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 integerswill be represented as a string.
问题分析:
题目的意思指:每一个数字串,从最高位开始读起,对应每个数字的个数x个,其值为y;则记为xy;且每个数字串与其前一个数字串相关;
这里是个很明显的递归,可以使用递归解法,也可以使用循环解法。两种解法核心都是统计数字串中每个数字连续出现的次数。
这里仅需判断当前数字与后一个数字是否相同,
若相同,则count++,计算重复的数据次数。直至该数字与后一个数字不同,或者到了数组尾部;此时将该数字的次数与其值添加入结果String即可。
代码:
递归解法:
public class Solution {
public String countAndSay(int n){
String result = "";
if (n <= 0)
return result;
return unitDo(n);
}
// 递归解法
private String unitDo(int n) {
if(n <= 1)
return "1";
String pre = unitDo(n - 1);
char[] datas = pre.toCharArray();
StringBuffer resultBuffer = new StringBuffer();
int count = 1;
for(int i = 0; i < datas.length; i++) {
if( (i >= datas.length - 1) || datas[i]!= datas[i + 1] ) {
resultBuffer.append(count);
resultBuffer.append(datas[i]);
count= 1;
}else {
count++;
}
}
return resultBuffer.toString();
}
}
非递归解法:
// 非递归解法
public String countAndSay2(int n){
String result = "";
if (n <= 0)
return result;
String pre = "1";
char[] datas;
StringBuffer resultBuffer;
int count;
for (int j = 1; j < n;j++) {
datas= pre.toCharArray();
resultBuffer= new StringBuffer();
count= 1;
//核心部分不变
for(int i = 0; i < datas.length;i++) {
if( (i >= datas.length - 1) || datas[i]!= datas[i + 1] ) {
resultBuffer.append(count);
resultBuffer.append(datas[i]);
count= 1;
}else {
count++;
}
}
pre= resultBuffer.toString();
}
return pre;
}