Leetcode 409. Longest PalindromeJAVA语言

本文介绍了一种求解字符串中能组成的最大回文串长度的算法。通过统计字符出现次数,利用回文串特性计算最长长度。适用于区分大小写的场景。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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.

题意:求解字符串中能组成的最大回文的长度。

public class Solution {

    public int longestPalindrome(String s) {

        int[] hash1=new int[26];

        int[] hash2=new int[26];

        for(int i=0;i<s.length();i++){

            if(s.charAt(i)>='a' && s.charAt(i)<='z'){

                

            hash1[s.charAt(i)-'a']++;

            }else{

                hash2[s.charAt(i)-'A']++;

            }

        }

        int odds=0;

        for(int i=0;i<26;i++){

            if(hash1[i]%2==1)odds++;

            if(hash2[i]%2==1)odds++;

        }

        if(odds==0)return s.length();

        return s.length()-odds+1;

        // int count=0;

        // int maxj=0;

        // int maxi=0;

        // for(int i=0;i<26;i++){

        //     if(hash1[i]%2==0){

        //         count=count+hash1[i];

        //     }else{

        //         if(hash1[i]>maxj){

        //             maxj=hash1[i];

        //         }else{

        //             count=count+hash1[i]-1;

        //         }

        //     }

        //     if(hash2[i]%2==0){

        //         count=count+hash2[i];

        //     }else{

        //         if(hash2[i]>maxi){

        //             maxi=hash2[i];

        //         }else{

        //             count+=hash2[i]-1;

        //         }

        //     }

        // }

        // int flag=Math.min(maxi,maxj);

        // int ret=0;

        // // if(flag==0)

        // // ret=0;

        // // else

        // ret=flag-1;

        // return count+Math.max(maxi,maxj)+ret;

    }

}

PS:

1、回文串左右对称,出现次数为偶数的肯定可以。

2、首先统计各个字母(区分大小写)的出现次数

3、出现次数为偶数的直接加到回文串长中。

4、出现次数为奇数的,最后只取最长的那一个全部加到回文串长中,其余的奇数的字母要全部减去1变成偶数。这也是一开始算错的地方。

所以如果没有出现次数为奇数的字母,直接返回字符串长;

有奇数次的字母出现,由于4,我们最后直接返回字符串长-奇数的个数+1;

+的1是最后的中心点~~~~。

上面的解法简介明了,不像我一开始的各种情况统计,麻烦。。。。。。。。。。。。。。。。。。


本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1890895

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值