5 javascript algorithm data-structures
我正在尝试用 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.
Run Code Online (Sandbox Code Playgroud)
所以我想创建一个传递N整数并赋予它值的函数
这是我的代码:
let countAndSay = function (A) {
if (A == 1) return "1"
if (A == 2) return "11"
let str ="11"
if(A > 2){
// count
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白如何构建它的逻辑。
您需要能够动态确定字符串具有的块的数量和类型,这可以使用正则表达式非常简洁地完成。要得出要在索引上解构的字符串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),
);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
344 次 |
| 最近记录: |