1.题目描述
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
2.示例
输入:s = “abccccdd”
输出:7
3.题解
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) {
count[c]++;
}
int num = 0;
for (int t : count) {
//如果是偶数就不变,奇数就减一
num += t/2*2;
//因为num一直是偶数,我们只允许有一个奇数作为回文字符串的中心
//所以我们只能取一个有奇数个的字符作为回文字符串的中心,然后
//num加一
if (t % 2 == 1 && num % 2 ==0) {
num++;
}
}
return num;
}
}
3.思路
回文字符串正读与反读都一样,所以我们可以遍历字符串算出每个字符出现的次数,然后有偶数个的可以放两边,奇数个的只能放在中间作为回文字符串的中心