【Leetcode Algorithm】Count and Say

来源:互联网 发布:淘宝客服设置分流 编辑:程序博客网 时间:2024/06/18 12:15

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 Solution {    public String countAndSay(int n) {        //使用StringBuffer来存储第n个序列        StringBuffer sb = new StringBuffer("1");        //从1到n逐次循环,计算第n个序列        for(int i=1;i<n;i++){            int j = 0;            //sbTmp用来临时存储第i个序列            StringBuffer sbTmp = new StringBuffer();            while(j<sb.length()){                //用k来记录相同的数字出现的次数                int k = 0;                //当出现不同的数时,调出循环                while(++k+j<sb.length()){                    if(sb.charAt(j)!=sb.charAt(j+k)){                        break;                    }                }                //添加次数k                sbTmp.append(k);                //添加相应的元素                sbTmp.append(sb.charAt(j));                //索引指向下一个元素                j += k;            }            //更新sb序列            sb = sbTmp;        }        return sb.toString();    }}


0 0
原创粉丝点击