一尘不染

检查字符串的排列是否可以成为回文

algorithm

编写一种方法来测试字符串是否满足成为回文条件的先决条件。

例如:

Input    | Output
mmo      | True  
yakak    | True  
travel   | False

我在想这种方法:

  1. 为T的所有排列制作一个后缀树,使得T $ Reverse(T)#
  2. 检查同一节点的所有排列

我有什么想念的吗?


阅读 379

收藏
2020-07-28

共1个答案

一尘不染

您真正要寻找的是是否所有(或除一个以外的)字母都配对了。只要它们是,它们就可以变成回文。

所以这就像…

bool canBeTurnedIntoAPalindrome(string drome)
{
  // If we've found a letter that has no match, the center letter.
  bool centerUsed = false;
  char center;

  char c;
  int count = 0;

  // TODO: Remove whitespace from the string.

  // Check each letter to see if there's an even number of it.
  for(int i = 0; i<drome.length(); i++)
  {
    c = drome[i];
    count = 0;

    for(int j = 0; j < drome.length(); j++)
      if (drome[j] == c)
         count++;

    // If there was an odd number of those entries
    // and the center is already used, then a palindrome
    // is impossible, so return false.
    if (count % 2 == 1)
    {
      if (centerUsed == true && center != c)
        return false;
      else
      {
        centerused = true;
        center = c;   // This is so when we encounter it again it
                      // doesn't count it as another separate center.
      }
    }
  }
  // If we made it all the way through that loop without returning false, then
  return true;
}

这不是最有效的方法(即使已经算过字母,它也会对字母进行多次计数),但它确实有效。

2020-07-28