Solution#2
public class Solution {
public int longestPalindrome(String s) {
if (s == null || s.length() == 0) return 0;
int[] lowercase = new int[26];
int[] uppercase = new int[26];
char[] ch = s.toCharArray();
for (char c : ch) {
if (c - 'a' >= 0) lowercase[c - 'a']++;
else uppercase[c - 'A']++;
}
int result = 0;
for (int i = 0; i < 26; i++) {
result += lowercase[i] / 2 * 2;
result += uppercase[i] / 2 * 2;
}
return result == s.length() ? result : result + 1;
}
}
Solution#1
public class Solution {
public int longestPalindrome(String s) {
int[] table = new int[52];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) - 'a' >= 0) {
table[26 + s.charAt(i) - 'a']++;
} else {
table[s.charAt(i) - 'A']++;
}
}
int result = 0;
int mid = 0;
for (int x : table) {
if (x % 2 == 0) result += x;
else {
if (x > mid) mid = x;
}
}
return result + mid;
}
}
Problem#1
- 对题目理解不清楚,即使是奇数个也可以抽出偶数个组成回文
- 不用判奇偶减一,可以统一处理
- 效率没有达到最高