检查JavaScript中回文的排列

我们需要编写一个JavaScript函数,该函数将字符串作为第一个也是唯一的参数。

我们函数的任务是检查字符串字符中的任何重排是否导致回文字符串。如果是,则我们的函数应返回true,否则返回false。

例如-

如果输入字符串是-

const str = 'amadm';

那么输出应该是-

const output = true;

因为该字符串可以重新排列以形成回文字符串“女士”。

示例

为此的代码将是-

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