Leetcode 题目解析之 Count and Say

2022-02-13 15:18:39 浏览数 (2)

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复制
    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;
    }

0 人点赞