重新排列字符串是回文

dj

我正在尝试解决以下问题:给定仅包含小写字母的字符串数组,请创建一个函数,以返回相同字符串的数组,但是每个字符串的字母都重新排列,从而使其成为回文(如果不可能的话)然后返回-1)。我对如何重新排列字母有些困惑。

let arr = ["hello", "racecra"];

我创建第一个检查的功能,如果一个词是回文:

function isPalindrome(arr) {
     let obj = {};

      for (var x = 0; x < str.length; x++) {

             if (obj[arr[x]]) {
                obj[arr[x]] += 1;
             } else {
                obj[arr[x]] = 1;
             }

      }

      let countOdd = 0;
      let countEven = 0; 
 
      for (let x of Object.values(obj)) {
           if (x % 2 == 0) {
              countEven += 1;
          } else {
               countOdd += 1;
          }

      }
      return countOdd == 1 ? true : false

}

然后我打算遍历单词

let emptyArr = [];

for (var x = 0; x < arr.length; x++) {
     if (isPalindrome(arr[x]) {
        // not sure what to do here.  I know the word is a palindrome but not sure how to sort the order of the word in the palindrome form. 
     } else {
        emptyArr.push(-1);
     }
}

return emptyArr;
Raina77ow

仔细观察:您不需要用单词来表示回文,您需要将它们重新排列为回文(“回文候选者”)。现在,如果一个单词的所有字母都可以用偶数(2、4、6等)计数,那么它就是回文候选者。

例如,这个...

hollo

...不是回文,但可以成为一个,因为其中有2个“ o”,2个“ l”和一个“ h”。要重新排列,只需在中间移动“ h”,然后在其前后放置“ o”和“ l”即可:

l -> o -> h <- o <- l

因此,首先将每个单词按字符分开,然后对这些字符进行计数或对其进行排序(如@Barmar建议的那样)。如果满足条件,则按照给定的方法重新排列字母;如果不是,则立即返回null(或其他可明显区分的其他特殊值)。


这是一种实现方法:

function rearrangeAsPalindrome(word) {
  if (word.length === 1) return word; // easy win first

  const charCounter = word.split('').reduce((counter, ch) => ({
    ...counter,
    [ch]: (counter[ch] || 0) + 1
  }), {});

  const parts = ['', '', '']; // left, middle, right 

  const entries = Object.entries(charCounter);
  for (let i = 0; i < entries.length; ++i) {
    const [char, counter] = entries[i];
    if (counter % 2) { // odd
      if (parts[1] !== '') return null;
      // one odd is already here, eject! eject!

      parts[1] = char.repeat(counter);
    } 
    else { // even
      const half = counter / 2;
      parts[0] = char.repeat(half) + parts[0];
      parts[2] += char.repeat(half);
    }
  }

  return parts.join('');
}

console.log(rearrangeAsPalindrome('racarrrac')); // crraaarrc
console.log(rearrangeAsPalindrome('aabbcc')); // cbaabc
console.log(rearrangeAsPalindrome('hollo')); // lohol
console.log(rearrangeAsPalindrome('hello')); // null

当该函数null意识到给定的单词不能重新排列为回文式-或如果可能的话,则返回该函数(并尽早执行)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章