1、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) {
unordered_map<char,int> result;
int count=0;
bool mid=false;
for(char a:s)
++result[a];
for(auto i=result.begin();i!=result.end();i++){
if((*i).second%2==0)
count+=(*i).second;
else{
count+=(*i).second-1;
mid=true;
}
}
if(mid)
++count;
return count;
}
};
通过一点小规律做的吧,当一种字母出现偶数次数时一定可以构成回文字,当是奇数x时,则一定有x-1个字母可以构成回文字,最终只要出现过奇数,则加一位。
无序容器复杂度为O(n),且可以很方便的统计每一类字母出现的次数。