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) {
if(s.empty())
return 0;
map<char, int> mp;
for(int i=0; i<s.length(); i++)
{
mp[s[i]] = ++mp[s[i]];
}
map<char, int>::iterator iter=mp.begin();
int maxlength = 0;
bool one = false;
for( ; iter!=mp.end(); iter++)
{
if(iter->second%2 == 0)
maxlength += iter->second;
else if(iter->second > 2)
{
maxlength += iter->second - 1;
one = true;
}else
{
one = true;
}
}
if(one)
maxlength += 1;
return maxlength;
}
};
本文介绍了一种算法,该算法能够从给定的字符串中找出可以构建的最长回文子串的长度。通过使用C++ map来记录每个字符出现的次数,此算法能够有效地确定最长回文子串,并考虑到大小写敏感的问题。
384

被折叠的 条评论
为什么被折叠?



