Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
int longestPalindrome(string s) { // time: O(n); space: O(1)
vector<int> record(52, 0);
int odd = 0;
for (char ch : s) {
if (isupper(ch)) ++record[ch - 'A'];
else ++record[ch - 'a' + 26];
}
for (int cnt : record) {
if (cnt & 1) ++odd;
}
return s.length() - odd + (odd > 0);
}
int longestPalindrome(string s) { // time: O(n); space: O(n)
int pair = 0;
unordered_set<char> st;
for (char ch : s) {
if (st.count(ch)) {
st.erase(ch);
++pair;
} else {
st.insert(ch);
}
}
return 2 * pair + !st.empty();
}