您的位置:首页 > 其它

LeetCode 038 Count and Say

2015-11-10 09:51 302 查看

题目描述

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.

代码

[code]    public String countAndSay(int n) {

        String init = "1";

        for (int i = 1; i < n; i++) {
            init = countAndSay(init);
        }

        return init;
    }

    String countAndSay(String string) {

        char[] str = string.toCharArray();

        String s = "";

        int p = 1;
        int count = 1;
        char last = str[0];

        for (; p < str.length; p++) {
            if (str[p] == last) {
                count++;
            } else {
                s += "" + count + last;
                count = 1;
                last = str[p];
            }
        }

        s += "" + count + last;

        return s;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: