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

检查字符串的排列是否可以成为回文,第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;}

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5090430.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存