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, 这个思路很不错