[LeetCode] 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.

Example:

Input:
"abccccdd"

Output:
7

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

给一个含有大写和小写字母的字符串, 找出能用这些字母组成的最长的回文。大小写敏感,字符长度不超过1010。

解法:由于字母可以随意组合,求出字符个数为偶数的字母,回文有两种形式,一种是左右完全对称,还有一种是以中间字符为中心,左右对称,统计出所有偶数个字符的出现总和,如果有奇数个字符的话,最后结果再加1。

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int longestPalindrome(String s) {
        if(s==null || s.length()==0) return 0;
        HashSet<Character> hs = new HashSet<Character>();
        int count = 0;
        for(int i=0; i<s.length(); i++){
            if(hs.contains(s.charAt(i))){
                hs.remove(s.charAt(i));
                count++;
            }else{
                hs.add(s.charAt(i));
            }
        }
        if(!hs.isEmpty()) return count*2+1;
        return count*2;
} 

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        ans = odd = 0
        cnt = collections.Counter(s)
        for c in cnt:
            ans += cnt[c]
            if cnt[c] % 2 == 1:
                ans -= 1
                odd += 1
        return ans + (odd > 0)

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
    def longestPalindrome(self, s):
        map = {}
        for i in s:
            if i in map:
                map[i] += 1
            else:
                map[i] = 1
        
        odd, even = 0, 0
        for key in map:
            if map[key] % 2:
                odd += 1
            else:
                even += 1
                 
        return even + 1 if odd else even

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import collections
 
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        odds = 0
        for k, v in collections.Counter(s).iteritems():
            odds += v & 1
        return len(s) - odds + int(odds > 0)
 
    def longestPalindrome2(self, s):
        """
        :type s: str
        :rtype: int
        """
        odd = sum(map(lambda x: x & 1, collections.Counter(s).values()))
        return len(s) - odd + int(odd > 0)

C++:

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    int longestPalindrome(string s) {
        int odds = 0;
        for (auto c = 'A'; c <= 'z'; ++c) {
            odds += count(s.cbegin(), s.cend(), c) & 1;
        }
        return s.length() - odds + (odds > 0);
    }
};

  

  

类似题目:

[LeetCode] 5. Longest Palindromic Substring 最长回文子串

[LeetCode] 125. Valid Palindrome 有效回文

[LeetCode] 9. Palindrome Number 验证回文数字

[LeetCode] 516. Longest Palindromic Subsequence 最长回文子序列

  

All LeetCode Questions List 题目汇总

posted @   轻风舞动  阅读(416)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示