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.
public class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int res = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
int odd = 0;
for (char c : map.keySet()) {
if (map.get(c) % 2 != 0) odd++;
if (odd <= 1) res += map.get(c);
else res += map.get(c) % 2 == 0 ? map.get(c) : map.get(c)-1;
}
return res;
}
}
public class Solution {
public int longestPalindrome(String s) {
if (s == null || s.length() == 0) return 0;
int odd = 0;
int len = s.length();
int[] upper = new int[26];
int[] lower = new int[26];
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c < 'a') upper[c-'A']++;
else lower[c-'a']++;
}
for (int i = 0; i < 26; i++) {
if (upper[i] % 2 != 0) odd++;
if (lower[i] % 2 != 0) odd++;
}
if (odd == 0) return len;
return len-odd+1;
}
}