首页 > 其他分享 >leetcode 409. Longest Palindrome

leetcode 409. Longest Palindrome

时间:2023-05-30 17:37:13浏览次数:41  
标签:Palindrome letters int odds length bool ans leetcode 409

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.
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        cnt = collections.Counter(s)        
        odds = sum(1 for v in cnt.values() if v&1)
        return len(s)-odds+bool(odds)

 补充:

>>> 1+bool('')
1
>>> 1+bool('1')
2
>>>

另外一种解法就是贪心:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        h = set()
        ans = 0
        for c in s:
            if c not in h:
                h.add(c)
            else:
                h.remove(c)
                ans += 2
        return ans + bool(h)

 

标签:Palindrome,letters,int,odds,length,bool,ans,leetcode,409
From: https://blog.51cto.com/u_11908275/6380977

相关文章

  • leetcode 747. Largest Number At Least Twice of Others
    Inagivenintegerarraynums,thereisalwaysexactlyonelargestelement.Findwhetherthelargestelementinthearrayisatleasttwiceasmuchaseveryothernumberinthearray.Ifitis,returntheindexofthelargestelement,otherwisereturn-1.Ex......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......
  • leetcode 674. Longest Continuous Increasing Subsequence
    Givenanunsortedarrayofintegers,findthelengthoflongestcontinuousincreasingsubsequence(subarray).Example1:Input:[1,3,5,4,7]Output:3Explanation:Thelongestcontinuousincreasingsubsequenceis[1,3,5],itslengthis3.Eventhough[1,3,5......
  • leetcode 746. Min Cost Climbing Stairs
    Onastaircase,thei-thstephassomenon-negativecostcost[i]assigned(0indexed).Onceyoupaythecost,youcaneitherclimboneortwosteps.Youneedtofindminimumcosttoreachthetopofthefloor,andyoucaneitherstartfromthestepwithin......
  • leetcode 541. Reverse String II
    Givenastringandanintegerk,youneedtoreversethefirstkcharactersforevery2kcharacterscountingfromthestartofthestring.Iftherearelessthankcharactersleft,reverseallofthem.Iftherearelessthan2kbutgreaterthanorequalt......
  • leetcode 504. Base 7
    Givenaninteger,returnitsbase7stringrepresentation.Example1:Input:100Output:"202"Example2:Input:-7Output:"-10"Note:Theinputwillbeinrangeof[-1e7,1e7].classSolution(object):defconvertToBase7(self,num):......
  • leetcode 350. Intersection of Two Arrays II
    Giventwoarrays,writeafunctiontocomputetheirintersection.Example:Givennums1=[1,2,2,1],nums2=[2,2],return[2,2].Note:Eachelementintheresultshouldappearasmanytimesasitshowsinbotharrays.Theresultcanbeinanyorder.Foll......
  • leetcode 83. Remove Duplicates from Sorted List
    Givenasortedlinkedlist,deleteallduplicatessuchthateachelementappearonlyonce.Forexample,Given1->1->2,return1->2.Given1->1->2->3->3,return1->2->3.#Definitionforsingly-linkedlist.#classListNode(object)......
  • leetcode 53. Maximum Subarray
    Givenanintegerarraynums,findthecontiguoussubarray (containingatleastonenumber)whichhasthelargestsumandreturnitssum.Example:Input:[-2,1,-3,4,-1,2,1,-5,4],Output:6Explanation: [4,-1,2,1]hasthelargestsum=6.Followup:Ifyouhavef......
  • leetcode 101. Symmetric Tree
    Givenabinarytree,checkwhetheritisamirrorofitself(ie,symmetricarounditscenter).Forexample,thisbinarytree[1,2,2,3,4,4,3]issymmetric:1/\22/\/\3443Butthefollowing[1,2,2,null,3,null,3]isnot:1/\2......