# Longest-Palindrome

Jan 16, 2018

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.

for(auto &p:wcount) ret += (p.second / 2);
ret *= 2;


int longestPalindrome(string s) {
unordered_map<char,int> wcount;
for(auto &c:s) wcount[c]++;
int ret = 0;
for(auto &p:wcount) ret += (p.second / 2);
ret *= 2;
return (ret < s.size())?ret+1:ret;
}


int longestPalindrome(string s) {
unordered_map<char,int> wcount;
for(auto &c:s) wcount[c]++;
int ret = 0;
for(auto &p:wcount) ret += ((p.second % 2)?p.second-1:p.second);
return (ret < s.size())?ret+1:ret;
}


dicuss有一个解法比较有趣，他是通过数出现奇数次的字母来实现的：

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() - odds + (odds > 0);
}

LeetCodeLeetCode

Rectangle-Area

Remove-Duplicates-from-Sorted-Array