最长回文串
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
示例 1:
输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = “a”
输入:1
示例 3:
输入:s = “bb”
输入: 2
(上述题目来源于LeetCode)
解法一(哈希表)
class Solution {
public int longestPalindrome(String s) {
//使用哈希表存储每个字符及其出现的次数,然后遍历哈希表
//如果出现次数为偶数的字符,一定会全部出现在最长回文串中,
//然后将该字符在哈希表中的出现次数改为0
//如果出现次数为奇数且大于1的字符,一定有出现次数减1的该字符出现在最长回文串中
//然后将该字符在哈希表中的出现次数改为1
//最后再遍历一次哈希表,如果有出现次数为1的字符,那么最长回文串的长度加1
int n = s.length();
int count = 0;
Map<Character,Integer> hashmap = new HashMap<>();
for(int i = 0;i < n;i++){
char ch = s.charAt(i);
hashmap.put(ch,hashmap.getOrDefault(ch,0) + 1);
}
for(Character i : hashmap.keySet()){
int num = hashmap.get(i);
if(num > 1){
if(num % 2 == 0){
count = count + num;
// hashmap.remove(i);
hashmap.put(i,0);
}else{
count = count + num - 1;
hashmap.put(i,1);
}
}
}
// if(hashmap.size() > 0){
// count++;
// }
for(Character i : hashmap.keySet()){
int num = hashmap.get(i);
if(num > 0){
count++;
break;
}
}
return count;
}
}
#####解法二
class Solution {
public int longestPalindrome(String s) {
int count = 0;
int[] list = new int[58];
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
list[ch - 'A']++;
}
for(int i : list){
if(i > 0){
if(i % 2 == 0){
count = count + i;
}else{
count = count + i / 2 * 2;
if(count % 2 == 0){
count++;
}
}
}
}
return count;
}
}