题意是:
n=1时输出字符串1;
n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
n=3时,由于上次字符是11,有2个1,所以输出21;
n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
依次类推,写个countAndSay(n)函数返回字符串。
public class Solution {
public String countAndSay(int n) {
if(n<1)
return null;
String str="1";//初始化字符串为1,当n == 1时,str =="1";
for(int i=1;i<n;i++)//递推,每次数前一次的字符串数字出现的个数配成新的字符串;
{
str=helper(str);
}
return str;
}
public String helper(String str)
{
char[]ch=str.toCharArray();
char pre=ch[0];
int count=1;
String result="";
for(int i=1;i<ch.length;i++)
{
if(ch[i]==pre)
{
count++;
}else
{
result=result+count+pre;//字符串连接的顺序;
pre=ch[i];
count=1;
}
}
result=result+count+pre;//最后一次的i == ch.length-1处的字符没有在for循环中输出,需要单独额外输出;
return result;
}既然我们把result的累加放在了当前字符与前一个字符不同的时候,那么不管str的最后一个字符是否与前一个字符相同,都应额外的累加在result中。
本文详细解析了CountAndSay算法的实现过程,该算法通过递归地构建字符串序列,每一步都统计上一步中数字的出现次数并形成新的字符串。文章提供了一个完整的Java实现示例。
2540

被折叠的 条评论
为什么被折叠?



