LeetCode Q 409 - Longest Palindrome
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
Code:
public int longestPalindrome(String s) {
if (s == null || s.length() == 0) return 0;
int[] count = new int[256];
for (char ch: s.toCharArray())
count[ch]++;
int maxLen = 0, hasOdd = 0;
for (int num: count) {
if (num == 0) continue;
if (num % 2 == 0) maxLen += num;
if (num % 2 == 1) {
hasOdd = 1;
if (num == 1) continue;
else maxLen += (num - 1); // "ccc" --> 3
}
}
return hasOdd == 0 ? maxLen : maxLen + 1;
}