题目
分析
我感觉直接判断有多少个成对字符,然后算起来看看要不要加1。可以使用unordered_map容器,判断字母出现次数。
代码
class Solution
{
public:
int longestPalindrome(string s)
{
unordered_map<char, int> count; 定义一个unordered_map容器
int sum = 0;
for (char c : s)
++count[c]; //遍历,统计字母出现次数
for (auto p : count)
{
int v = p.second;
sum += v / 2 * 2; // 计数
if (v % 2 == 1 and ans % 2 == 0) //判断是否要额外加1
++sum;
}
return sum;
}
};
测评结果
总结
巩固对unordered_map的使用。