题目
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
代码模板:
class Solution {
public int longestPalindrome(String s) {
}
}
分析
首先通过int[]来存每个字母存在的次数,根据这个次数来计算。
首先回文字符串需要满足若干个偶数+1个基数就能满足,所以如果能被2整除,直接加上这个count,如果不能被2整除,就加上count-1,并且标记一下single为1。
解答
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[58];
int sum = 0;
int single = 0;
for(int i = 0 ; i<s.length() ; i ++){
count[s.charAt(i)-'A']++;
}
for(int i = 0;i < count.length; i ++){
if(count[i] % 2 == 0){
sum += count[i];
}else{
single = 1;
sum += count[i] - 1;
}
}
return sum + single;
}
}