Problem
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example1
Input:
“abccccdd”
Output:
7
Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
Solution
偶数个的直接往上加。
奇数个的去掉一个往上加。如果有奇数个的字母,最后再加一。
class Solution {
public:
int longestPalindrome(string s) {
if(s.empty())
return 0;
unordered_map<char,int> hash_table;
for(auto &c :s)
{
hash_table[c]++;
}
int ret = 0;
int odd = 0;
unordered_map<char,int>::const_iterator it = hash_table.begin();
for(;it != hash_table.end();++it)
{
if(it->second % 2 == 0)
{
ret += it->second;
}
else
{
ret += it->second - 1;
odd = 1;
}
}
return ret + odd;
}
};