LeetCode-409 最长回文串

1. 题目

https://leetcode-cn.com/problems/longest-palindrome/

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

注意:
假设字符串的长度不会超过 1010。

示例 1:

输入:
"abccccdd"
输出:
7

解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

2. 我的AC

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        mapping = {}
        for char in s:
            if char not in mapping:
                mapping[char] = 1
            else:
                mapping[char] += 1
        count_odd = 0
        for _, num in enumerate(mapping.values()):
            if num % 2 == 1:
                count_odd += 1
        return len(s) - count_odd + 1if count_odd > 0 else len(s)

出错点注意:

  • aaa 可以只取 aa

3. 小结

  1. 遍历列表元素
  • 效率较低
for num in list:
  • 效率较高
for _, num in enumerate(list):
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容