给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。
数据是大小写敏感的,也就是说,"Aa"
并不会被认为是一个回文串。
注意事项
假设字符串的长度不会超过 1010
。
样例
给出 s = "abccccdd"
返回 7
一种可以构建出来的最长回文串方案是 "dccaccd"
。
public class Solution {
/**
* @param s a string which consists of lowercase or uppercase letters
* @return the length of the longest palindromes that can be built
*/
public int longestPalindrome(String s) {
// Write your code here
int result=0;
boolean hasRes = false;
int[] record = new int[52];
if(s.length()==0 || s ==null){
return 0;
}
for(int i = 0; i < 52;i++){
record[i] = 0;
}
//用一个字符数组负责统计每个字母个数,字母对应字符数组下标位置
for(int i = 0; i< s.length();i++){
int temp = s.charAt(i);
if(Character.isUpperCase(temp)){
record[temp-'A'+ 0]++;
} else {
record[temp-'a'+ 26]++;
}
}
for(int i = 0; i < 52;i++){
result += (record[i] / 2) * 2;
if(record[i] % 2 >0){
hasRes = true;
}
}
if(hasRes == true){
result++;
}
return result;
}
}