Description
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa"
is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
“abccccdd”Output:
7Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
Analysis
Count the frequence of each letter (uppercase and lowercase should be distincted) and sum all the even part of frequences, (technically, freq - freq % 2
). If any odd exists, return sum+1.
Code
class Solution {
public:
int longestPalindrome(string s) {
int lower[26] = {0},upper[26] = {0};
for (char c : s){
if (c>=97) lower[c-97]++;
else upper[c-65]++;
}
int result = 0;
bool odd = false;
for (int i: upper){
result += i - i % 2;
odd = (!odd && i % 2 != 0)? true : odd;
}
for (int i : lower){
result += i - i % 2;
odd = (!odd && i % 2 != 0)? true : odd;
}
return result + odd;
}
};
Appendix
- Link: https://leetcode.com/problems/longest-palindrome/
- Run Time: 3ms