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 size = 0 ;
int max = 0;
char[] charArr = s.toCharArray();
int count[] = new int[128];
//将所有字符串中的字符存入字符数组当中
for(int i=0;i<charArr.length;i++){
count[charArr[i]]++;
}
//遍历
for(int i=0;i<128;i++){
//由回文串的特点可知,为偶肯定可以当回文串元素
if(count[i]%2==0){
size += count[i];
}
//判断,如果比记录的max大,则加入前max-1的子串长度,否则直接加入
else if(count[i]%2!=0&&count[i]>max){
if(max!=0)
size = size + max -1;
max = count[i];
}else{
size +=count[i]-1;
}
}
return size+max;
}
}
lintCode627:最长回文串
最新推荐文章于 2019-09-11 18:37:00 发布