leetcode-409. Longest Palindrome 最长回文串的长度

来源:互联网 发布:淘宝上有铁匠铺吗 编辑:程序博客网 时间:2024/05/10 21:27

题目:

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:

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

题意:

给定一个字符串,求出可由这个字符串字符能构成的最长回文串的长度,区分大小写


代码:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
            
        tdict = dict() 
        for x in s:
            tdict[x] = 0
        for x in s:
            tdict[x] = tdict[x] + 1;
        result = 0
        flag = 0
        for i in tdict:
            if tdict[i] % 2 == 0:
                result = result + tdict[i]
            else :
                flag = 1
                result = result + tdict[i] - 1 
        if flag == 0:
            return result;
        else :
            return result + 1


笔记:

1、字典的定义:tdict = dict() 

2、判断字符x在字符串s中: if x in s:      

      判断字符x不在字符串s中: if x not in s:


0 0
原创粉丝点击