重新排列字符串,使相同字符相隔 n 个距离 JavaScript
我们需要编写一个 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP