409. Longest Palindrome(计算一组字符集合可以组成的回文字符串的最大长度)

本文介绍了一种算法,用于从给定的字符串中构建最长的回文子串。通过使用哈希表或数组,该算法能有效地找出并利用出现次数为偶数的字符,同时考虑是否可以添加一个出现奇数次的字符作为回文中心。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

解释:构成回文字符串,最好的情况就是所有出现双数的字母都排上,中间再加一个单着的

方法一:哈希表
class Solution {
    public int longestPalindrome(String s) {
        int count=0;
        int tip=0;
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        for(char c:s.toCharArray()){
           if(map.containsKey(c)) {
               int nums=map.get(c);
               map.put(c,nums+1);
           }else{
               map.put(c,1);
           }
        }
        
        for(char c:s.toCharArray()){
            if(map.containsKey(c)) {
               int nums=map.get(c);
               if(nums%2==1){
                   tip=1;
               }
                count+=nums/2;
                map.remove(c);
           }
        }
        return count*2+tip;
    }
}

 


方法二:数组
这种方法思路很简单,但是空间和时间消耗都很大。
class Solution {
    public int longestPalindrome(String s) {
        int[] chr = new int[256];
        for(char c:s.toCharArray()){
            chr[c]++;
        }
        int p=0;
        for(int c:chr){
            p+=(c/2)*2;
        }
        if(p<s.length()){
            p++;
        }
        return p;
    }
}

 

转载于:https://www.cnblogs.com/shaer/p/10847122.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值