查看我的FreeCodeCamp's Advanced Algorithm: No Repeats challenge解决方案:
返回所提供字符串的总排列数 没有重复的连续字母。
正确的代码应返回 2640 。有人可以向我解释这些错误消息吗?
RangeError:超出最大调用堆栈大小
在findFactorial:14:24
在findFactorial:21:14
在findFactorial:21:14
在findFactorial:21:14
在findFactorial:21:14
在findFactorial:21:14
注意:要获取错误所在的确切行号,请复制&将代码粘贴到此处:https://repl.it/
function permAlone(str) {
var final, factorial, repeated, i;
repeated = str.match(/([a-z])(?:.*)(\1)+/g);
if (str.length < 2) {
return 1;
}
// should return ["aa", "ff"]
if (repeated[0] === str) {
repeated[0] = repeated[0].split('').sort().join('').match(/([a-z])(?:.*)(\1)+/g);
repeated = repeated.reduce(function(a, b) {
return a.concat(b);
});
}
function findFactorial(n) {
if (n < 0) {
alert("No negative numbers accepted.");
}
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
}
factorial = findFactorial(str.length); // 7! = 5040
for (i = 0; i < repeated.length; i++) {
i++;
if (repeated.length === 1 && repeated.join("") !== str) {
final = factorial - findFactorial((str.length - 1)) * findFactorial(repeated[0].length);
} else if (repeated.length > 1 && repeated[i-1].length>2 || repeated[i].length>2) {
final = findFactorial(repeated[i].length) * findFactorial(repeated[i - 1].length);
} else {
final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1]) * findFactorial(repeated[i]));
// final = 5040 - ((6! * 2!)*2) + (5! * 2! * 2!);
}
}
return final;
}
permAlone('abfdefa'); // should return 2640
答案 0 :(得分:1)
tibsar指出你和我正确的方向。通过&#34; aa&#34;或&#34; ff&#34; findFactorial将继续调用自己,直到堆栈爆炸。除了检查负输入之外,您可以在findFactorial中添加防弹(检查非整数输入)。但与此同时,我在你的代码中找到了违规行:[你需要向右滚动才能看到坏部分和需要改变的内容,你忘了。长度两倍]
final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1]) * findFactorial(repeated[i]));
它应该是,
final = factorial - ((findFactorial((str.length - 1) * repeated[i].length) * (findFactorial(str.length - 1) * repeated[i - 1].length))) + (findFactorial(str.length - 2) * findFactorial(repeated[i - 1].length) * findFactorial(repeated[i].length));
碰巧,这似乎没有给出挑战的正确答案,但它确实解决了你所询问的错误。