题目:
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False, "aab"
-> True, "carerac"
-> True.
思路:
简单统计每一个字符的出现次数,如果出现奇数次的字符不超过1个,就说明可以构成回文串,否则就无法构成回文串。
代码:
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> hash;
for(int i = 0; i < s.length(); ++i) {
++hash[s[i]];
}
int odd_num = 0;
for(auto it = hash.begin(); it != hash.end(); ++it) {
if(it->second % 2 != 0) {
++odd_num;
}
}
return odd_num <= 1;
}
};