如何在javascript中构建计数和表示问题
我试图用JavaScript解决以下问题 count and say序列是如下开始的整数序列:如何在javascript中构建计数和表示问题,javascript,algorithm,data-structures,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 sequen
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
}
}
我不理解如何构建它的逻辑。您需要能够动态确定字符串的块数和类型,这可以通过正则表达式非常简洁地完成。要在索引
n
上找到要解构的字符串,递归调用count并说出
以获得n-1
的结果:
let countAndSay=函数(计数){
如果(计数==1){
返回“1”;
}
const digitsArr=countAndSay(count-1).match(/(\d)\1*/g);
//现在,您有了每个要构造的块的数组
//从1211年开始,你可以
// ['1', '2', '11']
return digitsArr//将上述内容转换为['11','12','21']:
.map(digitStr=>digitStr.length+digitStr[0])
.join(“”);//将上述内容转换为“111221”
};
console.log(
countAndSay(1),
countAndSay(2),
countAndSay(3),
countAndSay(4),
countAndSay(5),
);代码>这里有一个函数,它根据您输入的前一个字符串生成下一个数字字符串:
function next(s) {
s = s + "*"; // add a flag value at the end of the string
var output = "";
var j = 0;
for (var i = 1; i < s.length; i++) {
if (s.charAt(i) != s.charAt(i - 1)) { // if the character changes, concatenate the amount (i - j) and the digit
output += (i - j) + s.substring(j, j+1);
j = i;
}
}
return output;
}
功能下一个(s){
s=s+“*”;//在字符串末尾添加标志值
var输出=”;
var j=0;
对于(变量i=1;i
然后你需要递归地运行下一步
N次。@RahulChoudary我的道歉你可以运行这个程序吗?你可以共享jsfiddle
或任何编辑器链接来验证输出优雅的sinppet!。你能解释一下\1*
(在正则表达式中)的作用吗\2*
或\3*
为什么不起作用,因为它们都会出现在序列中?这是一个反向参考。(\d)
匹配一个数字,并将其放入捕获组。这是第一个(也是唯一一个)捕获组,因此再次匹配相同内容的语法是\1
。要匹配捕获组中匹配的相同字符的任意数量,请在其后面加一个*
\2
,\3
不起作用,因为该语法将匹配最近由第二个或第三个捕获组匹配的内容,但这些组在模式中不存在。请参阅,对于非常长的序列,甚至在D中有一个直接方法。