檢查 JavaScript 中迴文字串的排列


我們需要編寫一個 JavaScript 函式,它將一個字串作為第一個且唯一的引數。

我們的函式的任務是檢查字串中字元的任何重新排列是否會導致一個迴文串。如果是,那麼我們的函式應返回 true,否則返回 false。

例如,-

如果輸入字串是 -

const str = 'amadm';

那麼輸出應為 -

const output = true;

因為該字串可以重新排列以形成“madam”,這是一個迴文串。

示例

此程式碼為 -

 線上演示

const str = 'amadm';
const canFormPalindrome = (str = '') => {
   const hash = {};
   let count = 0;
   for (let i = 0; i < str.length; i++) {
      let c = str[i];
      if(c === ' '){
         continue;
      };
      if(hash[c]){
         delete hash[c];
      }else{
         hash[c] = true;
      };
      count++;
   };
   if(count % 2 === 0){
      return Object.keys(hash).length === 0;
   }else{
      return Object.keys(hash).length === 1;
   };
};
console.log(canFormPalindrome(str));

輸出

控制檯中的輸出為 -

true

更新於: 2021 年 2 月 26 日

588 次瀏覽

開啟您的職業

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.