[LeetCode]409. Longest Palindrome(最长回文)

409. 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.
(假设给定字符串的长度不会超过1,010。)

Example:

Input:
"abccccdd"

Output:
7

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

题目大意:
给定一个由小写或大写字母组成的字符串,找到可以用这些字母构建的最长的回文长度。
这是区分大小写的,例如“Aa”在这里不被视为回文。

错误思路: 思路是错误的!!!!!!!
刚开始以为求最大回文串长度,遍历字符串,求出各个字母数量,将所有的偶数相加,最后加上最大的奇数即可

代码如下:

//错误
    int longestPalindrome(string s) {//所有偶数加上一个最大的奇数
        int tmp[123] = {0};//a~z 65-9 A~Z 97-122
        int res=0;
        for(int i=0; i<s.size(); i++){
            tmp[s[i]] += 1;
        }
        for(int m=0; m<123; m++)//将所有数量为偶数的字母数量加起来
            if(tmp[m]>0 && tmp[m]%2==0)
                res += tmp[m];
        int maxOddNumber = 0;//最大的 数量为奇数的字母 的数量
        for(int n=0; n<123; n++)//将所有数量为奇数的字母数量加起来
            if(tmp[n]>0 && tmp[n]%2==1)
                if(tmp[n]>maxOddNumber)
                    maxOddNumber = tmp[n];
        cout <<  "maxOddNumber=" << maxOddNumber << endl;
        return res+maxOddNumber;
    }

正确思路: 思路是正确的!!!!!!!

回文串除中间字母外前后对称,也就是说,除了中间的字母外,其余的字母在回文中的数量必须是偶数。

发现奇数-1就是偶数,也能算到最大回文串长度中!
最大回文串长度 = 所有的偶数 + 所有的(奇数-1) + 1(有奇数+1 ,没奇数不加)

代码如下:

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
    //正确
    int longestPalindrome(string s) {//所有偶数+所有(大于1的奇数-1变成偶数)+1(有奇数+1 ,没奇数不加)
        int tmp[123] = {0};//a~z 65-9 A~Z 97-122
        int res=0;
        for(int i=0; i<s.size(); i++){
            tmp[s[i]] += 1;
        }
        bool a = false;//判断是否有奇数
        for(int m=0; m<123; m++){//将所有数量为偶数的字母数量加起来
            if(tmp[m]>0 && tmp[m]%2==0)
                res += tmp[m];
            if(tmp[m]>0 && tmp[m]%2==1){//所有的奇数-1变成偶数
                a = true;
                res = res + (tmp[m]-1);
            }
        }
        return a ? res+1 : res;//有奇数+1 ,没奇数不加
    }
};
int main()
{
    Solution a;
    string s;
    //cin >> s;
    s="civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
    cout << a.longestPalindrome(s) << endl;//应该是983
    return 0;
}
### 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、付费专栏及课程。

余额充值