僅從 JavaScript 中的字串中反轉子音


問題

我們要求編寫一個 JavaScript 函式,它以一個只包含小寫英語字母的字串作為唯一的引數。

該函式應構造一個新字串,其中子音的順序已反轉,母音保持其相對位置。

例如,如果函式的輸入為 -

const str = 'somestring';

那麼輸出應該為 -

const output = 'gomenrtiss';

示例

程式碼為 -

const str = 'somestring';
const reverseConsonants = (str = '') => {
   const arr = str.split("");
   let i = 0, j = arr.length - 1;
   const consonants = 'bcdfghjklnpqrstvwxyz';
   while(i < j){
      while(i < j && consonants.indexOf(arr[i]) < 0) {
         i++;
      }
      while(i< j && consonants.indexOf(arr[j]) < 0) {
         j--;
      }
      let tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
      i++;
      j--;
   }
   let result = "";
   for(let i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
};
console.log(reverseConsonants(str));

輸出

控制檯中的輸出將是 -

gomenrtiss

更新於: 2021 年 3 月 19 日

345 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.