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:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
Solution
class Solution {
public int longestPalindrome(String s) {
int[] lower = new int[26];
int[] upper = new int[26];
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) >= 'a') { // 'a' > 'A'
++lower[s.charAt(i) - 'a'];
} else {
++upper[s.charAt(i) - 'A'];
}
}
int longestPalinLen = 0;
for (int i = 0; i < 26; ++i) {
longestPalinLen += (lower[i] / 2) * 2 + (upper[i] / 2) * 2;
}
// if s is not fully used, there exists odd char count
return longestPalinLen == s.length() ?
longestPalinLen : longestPalinLen + 1;
}
}