知识点
map数据结构的使用
map的遍历方法
hash函数
代码
class Solution {
public:
int longestPalindrome(string s) {
map<char, int> node_map;
//记录每个字符出现的个数
for(int i = 0; i< s.length(); i++){
if( node_map.find(s[i]) == node_map.end() )
node_map[s[i]] = 0;
node_map[s[i]]++;
}
//迭代器
map<char, int>::iterator it;
int sum = 0;
int mediumFlag = 0;
for(it = node_map.begin(); it != node_map.end(); it++){
//如果该字符出现次数为偶数,则可对称摆放
if(it->second % 2 == 0) sum += it->second;
//如果出现次数为奇数,且未有中间字符,则一个字符放中间,其余对称摆放
else if(mediumFlag == 0) {
sum += it->second;
mediumFlag = 1;
}
//如果出现次数为奇数且已有中间字符,则丢弃一个字符,其余对称摆放
else sum += it->second -1;
}return sum;
}
};