重新排列字串,使相同字元相隔 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

更新日期: 31 年 8 月 2020 日

212 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.