javascript - 如何在javascript中建立计数和说出问题

标签 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.

所以我想创建一个通过 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/

相关文章:

与 jQuery AJAX 一起工作的 PHP 关联数组解决方案

javascript - 如何从javascript为按钮onclick选项创建一个函数

javascript - 无法显示从后端作为对象接收的数据,

javascript - jquery发送获取和更改图像源

子类化列表的 Pythonic 方式

c++ - Client Server场景下复杂且相互关联的数据结构

android - Recyclerview 删除之前选中的item的动画

ios - 用于过滤具有多个条件的列表的最佳选择算法?

algorithm - 创建建议词算法

algorithm - 找出哪个 token 属于哪个 AST 节点