您真正要寻找的是是否所有(或除一个以外的)字母都配对了。只要它们是,它们就可以变成回文。
所以这就像…
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;}
这不是最有效的方法(即使已经算过字母,它也会对字母进行多次计数),但它确实有效。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)