# 409. Longest Palindrome

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) {
int res = 0;
bool mid = false;
unordered_map<char, int> m;
for (char c : s) ++m[c];
for (auto it = m.begin(); it != m.end(); ++it) {
res += it->second;
if (it->second % 2 == 1) {
res -= 1;
mid = true;
}
}
return mid ? res + 1 : res;
}
};
``````

``````class Solution {
public:
int longestPalindrome(string s) {
unordered_set<char> t;
for (char c : s) {
if (!t.count(c)) t.insert(c);
else t.erase(c);
}
return s.size() - max(0, (int)t.size() - 1);
}
};
``````

``````class Solution {
public:
int longestPalindrome(string s) {
int odds = 0;
for (char c = 'A'; c <= 'z'; ++c) {
odds += count(s.begin(), s.end(), c) & 1;
}
return s.size() - max(0, odds - 1);
}
};
``````

Palindrome Pairs

Palindrome Permutation II

Palindrome Permutation

Shortest Palindrome

Palindrome Partitioning II

Palindrome Partitioning

Valid Palindrome

Palindrome Number

Longest Palindromic Substring

https://discuss.leetcode.com/topic/61338/what-are-the-odds-python-c

https://discuss.leetcode.com/topic/61574/very-easy-to-understand-java-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation