栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

所以这就像…

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;}

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号