前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Leetcode 题目解析之 Count and Say

Leetcode 题目解析之 Count and Say

原创
作者头像
ruochen
发布2022-02-13 15:18:39
发布2022-02-13 15:18:39
1.2K00
代码可运行
举报
运行总次数:0
代码可运行

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.

代码语言:javascript
代码运行次数:0
复制
    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;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档