Count and Say

来源:互联网 发布:深圳阿里云大厦图片 编辑:程序博客网 时间:2023/09/28 01:34

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.


代码如下:

public class CountAndSay {public String countAndSay(int n){StringBuilder curr = new StringBuilder("1");//curr作为当前串StringBuilder prev;//prev保存前一次的串int count;char say;for(int i=1;i<n;i++){prev = curr;//每一轮,都将当前保存的额串赋给prev保存curr = new StringBuilder();//新开辟一个空间给当前串count = 1;//count记录连续字符的个数say = prev.charAt(0);//say记录当前位置的字符int len = prev.length();for(int j=1; j<len; j++){if(prev.charAt(j) == say)count++;//找到看有多少个重复且连在一起的数字else{curr.append(count).append(say);//遇到不重复的数字时添加count = 1;say = prev.charAt(j);}}curr.append(count).append(say);}return curr.toString();}}


原创粉丝点击