409. 最长回文串

给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。

在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。

输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7

注意读清楚题,是构造而不是寻找

那么这道题就简单了,统计字符串各个字符出现的次数,偶数的都要上(放两边),奇数的选一个/ 大于2的取偶数部分,现在剩下的都是 奇数剩下的1个那部分,随机选一个就可

有点笨重的答案

class Solution {
    public int longestPalindrome(String s) {

       Map<Character,Integer> map = new HashMap<>();

       for(int i =0 ;i<s.length(); i++){
           map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
       }
        int res=0;
        boolean odd=false;
       for(Character c :map.keySet()){
           if(map.get(c)%2==0){
               res+=map.get(c);
           }
           else{
               if(odd==false){
                   res+=map.get(c);
                   odd = true;
               }else{
                   res+= (map.get(c)-1);
               }
           }
       }
       return res;
    }
}

优化之后

class Solution {
    public int longestPalindrome(String s) {
        int count[] = new int[128];
        for(char c : s.toCharArray()){
            count[c] ++;
        }
        int ans =0;
        for(int v:count){
            ans += v>>1<<1;
            if((v&1)==1 && (ans&1)==0){ 
                ans++;
            }
        }
        return ans;
    }
}