重新排列字符串,以使同一字符之间的距离变为n
我们需要编写一个JavaScript函数,该函数接受带有重复字符的字符串并返回一个新字符串,其中所有相同字符之间的距离恰好为n个字符。并且该数字应小于数组的长度。
例如-
If the input string is: "accessories" And the number n is 3 Then, The return value should be: "secrsecisao"
注意-可能会有一些其他排列来实现所需的输出,顺序并不重要,我们应该坚持逻辑,只要我们实现它,我们的输出就是正确的。
让我们为该函数编写代码-
示例
const str = 'accessories';
const equalDistance = (str, num) => {
const map = str.split("").reduce((acc, val) => {
const count = acc.get(val);
if(typeof count === 'number'){
acc.set(val, count+1);
}else{
acc.set(val, 1);
};
return acc;
}, new Map());
const arr = Array.from(map).sort((a, b) => b[1] - a[1]);
let newString = '';
for(let i = 0, count = 0; i < str.length;){
if(!arr[count][1]){
arr.splice(count, 1);
continue;
};
newString += arr[count][0];
arr[count][1]--;
i++;
count = i % num;
};
return newString;
};
console.log(equalDistance(str, 4));
console.log(equalDistance('abb', 2));
console.log(equalDistance('aacbbc', 3));输出结果
控制台中的输出将为-
sceasceosri bab acbacb