409. Longest Palindrome
set, map, array的基本用法,优先使用array; palindrome性质(允许存在一个字符为奇数的字符串)
1.set:
public int longestPalindrome(String s) {
Set<Character> set = new HashSet<>();
int count = 0;
for (char a : s.toCharArray()) {
if (set.contains(a)) {
set.remove(a);
count++;
} else {
set.add(a);
}
}
return set.isEmpty() ? count * 2 : count * 2 + 1;
}
2.array:
public int longestPalindrome(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) {
count[c]++;
}
int res = 0;
int odd_count = 0;
for (int value : count) {
if (value % 2 == 1) odd_count++;
res += value;
}
return odd_count > 0 ? res - odd_count + 1 : res;
}