给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
实例1:
输入:
“abccccdd”
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
map统计字符次数,偶数个字符就加上全部,奇数个字符就减一之后再加,最后如果有落单的奇数再加一个1即可。
class Solution {
public:
int longestPalindrome(string s) {
map<char, int> hashmap;
int ans = 0;
bool odd = true;
for (char c: s){
hashmap[c]++;
}
typedef map<char, int>::iterator iter;
iter it = hashmap.begin();
while (it != hashmap.end()){
if (it->second % 2 == 0){
ans += it->second;
}
else {
ans += it->second - 1;
if (odd){
ans += 1;
odd = false;
}
}
it++;
}
return ans;
}
};