leetcode之Longest Palindrome(409)

题目:

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

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

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

示例 1:

输入:
"abccccdd"

输出:
7

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

python代码1:

class Solution(object):
    def longestPalindrome(self, s):
        for i in s:
            if i in char_dict:
                char_dict[i] += 1
            else:
                char_dict[i] = 1
        for i in char_dict:
            if char_dict[i] % 2 == 0:
                sum += char_dict[i]
            elif char_dict[i] % 2 == 1:
                sum += char_dict[i]-1
                single = 1
        return sum + single

python代码2:

class Solution:
    def longestPalindrome(self, s):
        res = 0
        for n in collections.Counter(s).values():
            res += n - int(n % 2)
        return res + int(res < len(s))

心得:哈希表速度确实快一些。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章