LeetCode 409. Longest Palindrome(Java)

本文介绍了一种算法,用于从给定字符串中构建最长的回文串,并详细解释了其实现过程。通过使用字符计数和判断奇偶性的方法,确保了高效地找出构成回文串的所有可能字符。

摘要生成于 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.


题意:
求用所给字符串的字符元素组成最长回文串的长度。


思路:
1.利用数组map[256]将每个字符出现的次数保存起来;
2.用计数器count作为计数变量,再遍历一次字符数组,看字符串中是否出现次数为奇数的元素,如果出现,置count=1;
3.遍历map数组,如果map[i]为偶数,则说明可以作为最长回文串的一部分,如果map[i]为奇数,那么map[i]-1也可以作为最长回文串的一部分;
4.最后返回count即可。


代码:

public class Solution {
    public int longestPalindrome(String s) {
        if (s.length() == 0) {
            return 0;
        }
        int[] map = new int[256];
        for(int i = 0;i < s.length();i++){
            map[s.charAt(i)]++;
        }
        int count = 0;
        for(int i = 0;i < s.length();i++){
            if(map[s.charAt(i)] % 2 == 1){
                count = 1;
            }
        }
        for(int temp:map){
            if(temp % 2 == 0){
                count += temp;
            }
            if(temp > 2 && temp % 2 == 1){
                count += temp - 1;
            }
        }
        return count;
    }
}
### LeetCode 第 5 题 '最长回文子串' 的 Python 解法 对于给定字符串 `s`,返回其中的最长回文子串是一个经典算法问题。一种高效的解决方案是利用中心扩展方法来寻找可能的最大长度回文。 #### 中心扩展法解析 该方法基于观察到的一个事实:一个回文串可以由中间向两端不断扩散而得。因此可以从每一个字符位置出发尝试构建尽可能大的回文序列[^1]。 具体来说: - 对于每个字符作为单个字符的中心点; - 或者两个相同相邻字符作为一个整体中心点; - 向两侧延伸直到遇到不匹配的情况为止; 记录下每次找到的有效回文串及其起始索引和结束索引,并更新全局最优解。 下面是具体的 Python 实现代码: ```python def longest_palindrome(s: str) -> str: if not s or len(s) == 0: return "" start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max(len1, len2) if max_len > end - start: start = i - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end + 1] def expand_around_center(s: str, left: int, right: int) -> int: L, R = left, right while L >= 0 and R < len(s) and s[L] == s[R]: L -= 1 R += 1 return R - L - 1 ``` 此函数通过遍历整个输入字符串并调用辅助函数 `expand_around_center()` 来计算以当前位置为中心能够形成的最长回文串长度。最终得到的结果即为所求的最大回文子串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值