38. Count and Say

来源:互联网 发布:tipso.min.js 编辑:程序博客网 时间:2024/06/05 19:06

解题思路:设置一个count来计数,ch为上次记录的字符,一共有n次操作,每次操作的输入字符为前一次产生的string,因此这里面使用到了一个二重for循环,代码如下:

public static String countAndSay(int n) {        String string="1";        for (int i = 0; i < n; i++) {            char ch=string.charAt(0);            StringBuffer temp=new StringBuffer();            int count=1;            for (int j = 1; j < string.length(); j++) {                if (string.charAt(j)==ch) count++;                else {                    temp.append(count);                    temp.append(ch);                    ch=string.charAt(j);                    count=1;                }            }            temp.append(count);            temp.append(ch);            string=temp.toString();        }        return string;    }
0 0