Count and Say 2014/10/23

public class solution
{
public static void main(String[] args)
{
System.out.println(countAndSay(12));
//String s="23";
//int r=s.length();
//System.out.println("11111111111111111");
}

public static String countAndSay(int n)
{

if(n == 1){
return "1";
}

String s="1";
StringBuffer str=new StringBuffer();
int i;
int cnt=0;
int round=0;//迭代次数

while (++round<n)
{
cnt=1;//计数
str.setLength(0);//设置长度
for(i=1;i<s.length();i++)
{
if(s.charAt(i)==s.charAt(i-1))//发现重复字符
//str.charAt(i-1)++;//首位相加
{cnt++;}
else
{cnt=1;
str.append(cnt).append(s.charAt(i-1));
}//将出现次数和数字记录在str中
//s = str.toString();//将str转化为s;
//如果i和i-1不一样,记录i-1出现的次数
}
str.append(cnt).append(s.charAt(i-1)); //这句话的意义
s = str.toString();
}
return s;
//return str.toString();
}
}

原文地址:https://www.cnblogs.com/bowiehsu/p/4046706.html