javascript - 如何在javascript中建立计数和说出问题
问题描述
我正在尝试在 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
}
}
我不明白如何构建它的逻辑。
解决方案
您需要能够动态确定字符串具有的块的数量和类型,这可以使用正则表达式非常简洁地完成。要提出要在 index 上解构的字符串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),
);