Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome here.
思路
首先学习一个新单词,palindrome回文。
主要思路是哈希表+贪心,随后对哈希表进行遍历。当元素值是奇数时,需要用一个flag记录一下出现过奇数的,sum累加上奇数值-1(因为当有多个奇数出现时,不可能直接拼接成一个回文串);当元素是偶数时,sum直接累加上偶数值。在循环结束后,若flag为true,表明组成的回文串中有出现奇数次数的字母,因此sum需要再加上1。
代码
class Solution {
public:int longestPalindrome(string s) {unordered_map<char, int> letter_map;for(auto c : s){letter_map[c]++;}int sum = 0, temp;bool flag = false;for(auto it : letter_map){temp = it.second;if(temp % 2 == 1){sum += temp - 1;flag = true;}else {sum += temp;}}if(flag == true)sum += 1;return sum;}
};