[leetcode] problem 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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int (String s) {
int[] count = new int[128];
int result = 0;
boolean isOdd = false;

for (char ch : s.toCharArray()) {
int idx = ch - '0';
count[idx]++;
}

for (int chCount : count) {
if (chCount % 2 != 0)
isOdd = true;

result += (chCount >> 1) * 2;
}

return isOdd ? result + 1 : result;
}