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.

Example
Given s = "abccccdd" return 7
One longest palindrome that can be built is "dccaccd", whose length is 7.

思路:
回文串主要有两种形式,一个是左右完全对称的,一种是以中间字符为中心,左右对称。我们使用字典,第一次出现,把元素加入字典,值设为True,再次出现时用del移除元素。结束循环后字典如有元素,则最长是以中间字符为中心左右对称的,即是字符串长度-字典长度+1。

class Solution:
    """
    @param s: a string which consists of lowercase or uppercase letters
    @return: the length of the longest palindromes that can be built
    """
    def longestPalindrome(self, s):
        # write your code here
        hash = {}
        
        for c in s:
            if c in hash:
                del hash[c]
            else:
                hash[c] = True
        
        remove = len(hash)
        if remove > 0:
            remove -= 1
        
        return len(s) - remove
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容