哈希表
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> count;
int ans = 0;
for (char c : s)
++count[c];
for (auto p : count) {
int v = p.second;
ans += v / 2 * 2;
/ 发现了第一个出现次数为奇数的字符后,我们将 ans 增加 1,这样 ans 变为奇数,
/ 在后面发现其它出现奇数次的字符时,我们就不改变 ans 的值了。
if (v % 2 == 1 and ans % 2 == 0)
++ans;
}
return ans;
}
};
或
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char,int> count;
for(char ch:s)count[ch]++;
int res=0;
for(auto it:count){
if(it.second&1)res+=it.second-1; / 加上奇数字符数-1
else res+=it.second; / 加上偶数字符数
}
return res<s.size()?res+1:res; / 加上一个单字符放在中间
}
};
数组保存
在这道题上优势不大
class Solution {
public:
int longestPalindrome(string s) {
int hashCount[52] = {0};
for(int i = 0; i < s.size(); i++) {
if('a' <= s[i] && s[i] <= 'z') {
hashCount[s[i]-'a']++;
} else {
hashCount[s[i]-'A'+26]++;
}
}
int sum = 0;
for(int i = 0; i < 52; i++) {
if((sum&1) && (hashCount[i]&1)) {
sum += hashCount[i]-1;
} else {
sum += hashCount[i];
}
}
return sum;
}
};