409. Longest Palindrome

原题网址:https://leetcode.com/problems/longest-palindrome/

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) {
        char[] sa = s.toCharArray();
        int[] frequency = new int[52];
        for(char ch : sa) {
            if ('A' <= ch && ch <= 'Z') {
                frequency[ch - 'A'] ++;
            } else {
                frequency[ch - 'a' + 26] ++;
            }
        }
        boolean single = false;
        int len = 0;
        for(int f : frequency) {
            single |= (f & 1) == 1;
            len += f / 2;
        }
        return len * 2 + (single ? 1 : 0);
    }
}


最长回文子串(Longest Palindrome Substring)是一个经典的字符串处理问题。给定一个字符串,要求找到其中最长的回文子串。回文串是指正读和反读都一样的字符串,例如"madam"和"racecar"。 解决这个问题的方法有很多,其中最常用的是中心扩展法和动态规划法。 ### 方法一:中心扩展法 中心扩展法的基本思想是遍历字符串的每一个字符,以该字符为中心,向两边扩展,找到最长的回文子串。需要注意的是,回文串的长度可能是奇数也可能是偶数,因此需要分别处理。 ```python def longest_palindrome(s): if not s: 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, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return right - left - 1 # 示例 s = "babad" print(longest_palindrome(s)) # 输出 "bab" 或 "aba" ``` ### 方法二:动态规划法 动态规划法的基本思想是将字符串的所有子串的子问题结果存储在一个二维数组中,然后通过已知的子问题结果推导出更大问题的结果。 ```python def longest_palindrome_dp(s): if not s: return "" n = len(s) dp = [[False] * n for _ in range(n)] start, max_len = 0, 1 for i in range(n): dp[i][i] = True for i in range(n - 1): if s[i] == s[i + 1]: dp[i][i + 1] = True start = i max_len = 2 for l in range(3, n + 1): for i in range(n - l + 1): j = i + l - 1 if s[i] == s[j] and dp[i + 1][j - 1]: dp[i][j] = True if l > max_len: start = i max_len = l return s[start:start + max_len] # 示例 s = "babad" print(longest_palindrome_dp(s)) # 输出 "bab" 或 "aba" ``` 这两种方法各有优缺点,中心扩展法实现简单,时间复杂度为O(n^2),而动态规划法虽然时间复杂度相同,但空间复杂度较高。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值