leetcode原题的地址链接:https://oj.leetcode.com/problems/count-and-say/
题目内容如下:
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 可以读成 1个1, 所以下一个数是11
11 可以读成2个1,所以下一个数是21
21 可以读成1个2,1个1,所以下一个数就是1211
1211 可以读成1个1,1个2,2个1,所以下一个数就是 111221
111221 可以读成3个1,2个2,1个1,所以下一个数就是 312211
从上述例子知道,下一个数就是上一个数的读法
解题报告:
从题目意思来看,我们需要定义这么几个变量
1、StringBuffer类型的res,用来作为字符串的缓冲区
2、String s 用来表示返回最后的字符串
3、int cnt ; 用来作为字符串缓冲区的临时字符串值
4、int round 迭代次数
完整代码:
该代码是来自http://blog.youkuaiyun.com/fightforyourdream/article/details/12901505 ,支持原创,我在原创代码的里添加了自己对代码理解的注释
package string;
public class S38{
public static void main(String[] args){
S38 s = new S38();
System.out.println(s.countAndSay(6));
}
public String countAndSay(int n){
if(n == 1)
return "1";
//定义最后返回的字符串s
String ss="1";
//定义字符串缓冲区res
StringBuffer res = new StringBuffer();
//定义res里的元素cnt
int cnt=0;
//定义迭代次数round
int round=0;
int i;
while(++round < n)
{
cnt = 1;
res.setLength(0);//setLength()设置字符串的长度为0
for(i=1;i<ss.length();i++){
if(ss.charAt(i) == ss.charAt(i-1))//charAt :在字符序列ss中返回规定索引i对应的字符型取值
cnt++;
else{
res.append(cnt).append(ss.charAt(i-1));//append:粘贴指定字符串到指定字符序列res中
cnt=1;
}
}
res.append(cnt).append(ss.charAt(i-1));
ss=res.toString();//toString(): 返回字符串代表值
}
return res.toString();
}
}