Longest Palindrome

Leetcode 409.

Version 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int longestPalindrome(String s) {
int length = s.length();
int[] arr = new int[58];
for(int i = 0; i < length;i++){
arr[s.charAt(i) - 'A']++;
}
int max = 0;
int oddMax = 0;
int passedIndex = 0;
for(int i = 0; i < arr.length;i++){
int value = arr[i];
if(value % 2 == 0){
//value is even
max += value;
}else{
//value is odd
max += value - 1;
}
}
if(max < length)
max++;
return max;
}
}

Version 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int longestPalindrome(String s) {
int length = s.length();
int[] arr = new int[58];
for(int i = 0; i < s.length();i++){
arr[s.charAt(i) - 'A']++;
}
int count = 0;
for(int value : arr){
count += value % 2;
}

return count == 0 ? length : length - count + 1;
}
}