问题描述:从一个字符串中构建回文子字符串(大小写敏感)。返回最长回文子字符串长度。
思路:出现次数为偶数次的字符串全部采用,出现次数为奇数次的将出现次数最大的采用。其余的采用次数-1。
原答案:
public int longestPalindrome(String s) {
char [] c=s.toCharArray();
int [] record=new int['z'-'A'+1];
for(int i=0;i<c.length;i++){
record[c[i]-'A']++;
}
int maxOdd=0;
int total=0;
for(int j=0;j<record.length;j++){
if(record[j]%2==0)
total+=record[j];
else{
total+=Math.max(0,Math.min(maxOdd,record[j])-1);
maxOdd=Math.max(maxOdd,record[j]);
}
}
return maxOdd+total;
}
最佳答案:
public int longestPalindrome(String s) {
int[] letters = new int[58];
char[] ch = s.toCharArray();
int res = 0;
boolean hasSingleLetter = false;
for (char c : ch) {
letters[c - 'A']++;
}
for (int i : letters) {
if (i % 2 == 0) {
res += i;
} else {
if (i > 1) {
res += i-1;
}
hasSingleLetter = true;
}
}
return res + (hasSingleLetter ? 1 : 0);
}
思路一致,但是奇数的处理要更好。