我正在尝试在 JavaScript 中解决以下问题
count-and-say 序列是如下开头的整数序列:
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.
Example:
if n = 2,
the sequence is 11.
所以我想创建一个通过
N
的函数整数并赋予它值这是我的代码:
let countAndSay = function (A) {
if (A == 1) return "1"
if (A == 2) return "11"
let str ="11"
if(A > 2){
// count
}
}
我不明白如何构建它的逻辑。
最佳答案
您需要能够动态确定字符串具有的 block 的数量和类型,这可以使用正则表达式非常简洁地完成。提出要在索引 n
上解构的字符串, 递归调用 countAndSay
得到 n - 1
的结果:
let countAndSay = function (count) {
if (count === 1) {
return '1';
}
const digitsArr = countAndSay(count - 1).match(/(\d)\1*/g);
// You now have an array of each chunk to construct
// eg, from 1211, you get
// ['1', '2', '11']
return digitsArr // Turn the above into ['11', '12', '21']:
.map(digitStr => digitStr.length + digitStr[0])
.join(''); // Turn the above into '111221'
};
console.log(
countAndSay(1),
countAndSay(2),
countAndSay(3),
countAndSay(4),
countAndSay(5),
);
关于javascript - 如何在javascript中建立计数和说出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60784091/