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.
Example:
Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
关键思想:如果一个字符串是回文,那么出去该字符串中间的那个字符,余下的一定是成双出现。
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, bool> m;
int ans = 0;
for (char c : s) {
if (m.find(c) == m.end()) m[c] = true;
else if (m[c] == true) {
m[c] = !m[c];
ans += 2;
}
else m[c] = true;
}
for (auto it = m.begin(); it != m.end(); it++) if (it->second) return ans + 1;
return ans;
}
};