1. 題目
2. 思路
字符計數
偶數必然可用於構成迴文
奇數只需-1,即可構成迴文
在有奇數的情況下,最後需要+1
[aabbc
aabb]
3. 代碼
class Solution {
public:
int longestPalindrome(string s) {
// 字符計數
unordered_map<char, int> temp;
for(char c : s){
temp[c]++;
}
// 計算可形成迴文的字符數
int ans = 0;
bool singal = false;
for(auto it : temp){
// 偶數必然可構成迴文
if(it.second % 2 == 0){
ans += it.second;
}else{ // 奇數 -1
singal = 1;
ans += it.second - 1;
}
}
// 奇數存在:補充
return ans + singal;
}
};