2
头图

Appearance series

Title description: Given a positive integer n, output the nth item of the appearance sequence.

"Appearance sequence" is a sequence of integers, starting from the number 1, each item in the sequence is a description of the previous item.

You can think of it as a sequence of numeric strings defined by a recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is a description of countAndSay(n-1), and then converted into another number string.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/count-and-say/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Iteration
If n is 1, directly return "1"; if n is greater than 1, record last as the last string sequence, initially "1", curNum records the current character number, curNumCount records the number of consecutive occurrences of the current character number, and cur is the current Need to get the string sequence, traverse last, get the number of consecutive occurrences of each character number, get cur, then assign cur to last, continue the next round of processing, and finally return cur.
public class LeetCode_038 {
    public static String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        String last = "1", cur = "";
        char curNum;
        int curNumCount = 0;
        for (int i = 2; i <= n; i++) {
            cur = "";
            curNum = last.charAt(0);
            curNumCount = 1;
            for (int x = 1; x < last.length(); x++) {
                if (last.charAt(x) == curNum) {
                    curNumCount++;
                } else {
                    cur += curNumCount + "" + curNum;
                    curNum = last.charAt(x);
                    curNumCount = 1;
                }
            }
            cur += curNumCount + "" + curNum;
            last = cur;
        }
        return cur;
    }

    public static void main(String[] args) {
        System.out.println(countAndSay(5));
    }
}
【Daily Message】 mountain has a peak, and the sea has another shore. After a long journey, there will be a turnaround. The aftertaste is bitter and sweet in the end.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!