当前位置: 首页 > 工具软件 > Say.js > 使用案例 >

Count and Say - JS

魏航
2023-12-01

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.

Subscribe to see which companies asked this question

Tags

String

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

DP Solution

/**
 * @param {number} n
 * @return {string}
 */

function read(str) {
    var len = str.length;
    if (len === 1) {
        return "1" + str[0];
    }

    var count = 1;
    var target = str[0];
    var ret = "";

    for (var k = 1; k < len; k++) {
        while (str[k] === target) {
            count++;
            k++;
        }
        ret += count + str[k - 1];
        if (k >= len) {
            return ret;
        } else {
            count = 1;
            target = str[k];
        }
    }

    ret += count + str[len - 1];

    return ret;
}

var countAndSay = function (n) {
    if (n <= 0) {
        return "";
    }

    var f = [];
    f[0] = "1";
    for (var i = 1; i < n; i++) {
        f[i] = read(f[i - 1]);
    }

    return f[n - 1];
};


 类似资料: