我们需要编写一个JavaScript函数,该函数将字符串作为第一个参数,即str,将数字称为num,作为第二个参数。
该函数应该计算可以从给定字符串str构造的所有长度为num的回文字符串的数目。然后,该函数应最终返回计数。
例如-
如果输入的字符串和数字为-
const str = 'ij'; const num = 4;
那么输出应该是-
const output = 4;
因为这四个可能的回文字符串是-
'iiii', 'jjjj', 'ijji', 'jiij'
我们将首先使用哈希集计算给定字符串中唯一字母的数量。如果回文的长度是奇数,则中间字符可以有u个选择,其中u是字符串中唯一字符的计数。
当num是偶数时,我们将有以下可能性-
power(u, num/2)
而且当num为奇数时,我们需要将此数字乘以u,因为我们有该位置的u选择。
以下是代码-
const str = 'ij';
const num = 4;
const findValidPalindromes = (str = '', num = 1) => {
const set = new Set();
for(let i = 0; i < str.length; i++){
const el = str[i];
set.add(el);
};
const u = set.size;
if(num & 1){
return Math.pow(u, num/2) * u;
}else{
return Math.pow(u, num/2);
};
};
console.log(findValidPalindromes(str, num));输出结果以下是控制台输出-
4