Question
Given a string, determine if a permutation of the string could form a palindrome.
For example,
“code” -> False, “aab” -> True, “carerac” -> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Show Tags
Show Similar Problems
我的思路,用map<char,int>统计字符出现的次数,如果都是偶数次肯定可以左右对称。
如果仅1个字符出现一次,也可以回文,否则不回文。
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<char, int> word_count;
string a;
cin >> a;
for (int i = 0; i != a.size(); i++)
{
++word_count[a[i]];
}
int odd = 0;
for (int i = 0; i != a.size(); i++)
{
if (word_count[a[i]] % 2 != 0)
odd++;
}
if (odd >1)
cout << "不回文" << endl;
else cout << "回文" << endl;
return 0;
}