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