Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.ide
This is case sensitive, for example "Aa" is not considered a palindrome here.ui
Note:
Assume the length of given string will not exceed 1,010.code
Example:索引
Input:
"abccccdd"ip
Output:
7leetcode
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.get
it->second & 0x1==0
的錯誤class Solution { public: int longestPalindrome(string s) { unordered_map<char, int> mp; int sum = 0; bool containOdd = false; // for (int i = 0; i < s.size(); i++) mp[s[i]]++; for (auto it = s.cbegin(); it != s.cend(); it++) mp[*it]++; for (auto it = mp.cbegin(); it != mp.cend(); it++) if (it->second & 0x1) { sum += it->second - 1; containOdd = true; } else sum += it->second; return sum + containOdd; } };
int longestPalindrome(string s) { vector<int> count(256); for (char c : s) ++count[c]; int odds = 0; for (int c : count) odds += c & 1; return s.size() - odds + (odds > 0); }
+(odds > 0)
完成的邏輯是:若是存在奇數的字母, 則最總體可爲奇數的迴文, 不存在奇數則不進行修正.s.size()
減去1, 這個思路很不錯