解题思路: 一次AC,统计字符串中每个字符出现的次数,偶数个就直接累加,奇数个减一再求和,最后返回值需要注意,含有奇数的字符时,返回结果为count+1,若只有偶数的字符,直接返回count.
class Solution {
public:
int longestPalindrome(string s) {
map<char,int>res;
for(int i = 0; i < s.length(); i++){
res[s[i]]++;
}
int count = 0;
bool flag = 0;
map<char,int>::iterator it;
for(it = res.begin(); it != res.end(); it++){
if(it->second % 2 == 0)
count += it->second;
else{
count += (it->second -1);
flag = 1;
}
}
if(flag == 1)
return count +1;
else
return count;
}
};