My Python Solution using hashmap with Comments


  • 0
    S
    def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: int
            """
            hashmap={}
            maxlen=0
            maxodd=0
            k=0
            flag=0
            for i in range(0,len(s)):
                hashmap[s[i]]=0
            for i in range(0,len(s)):
                hashmap[s[i]]+=1
            #print hashmap   
            for i in range(0,len(s)):
                if hashmap[s[i]]%2!=0:
                    if maxodd<hashmap[s[i]]:
                       maxodd=max(maxodd,hashmap[s[i]])  #NOTE MAX ODD OCURRENCE  AND SET ITS FREQ TO ZERO BACAUSE IT IS USED COMPLETELY
                       flag=1
                       k=i
            if flag==1:           
              hashmap[s[k]]=0# FREQ SET TO ZERO OF MAX ODD OCURRENCE           
            for i in range(0,len(s)):
                if hashmap[s[i]]!=0 and hashmap[s[i]]%2==0: # ADD ALL EVEN OCURRENCE AND SET ITS FEQ TO ZERO 
                    maxlen+=hashmap[s[i]]
                    hashmap[s[i]]=0
                    #print maxlen
                elif hashmap[s[i]]!=0:
                    maxlen+=hashmap[s[i]]-1  # ADD ODD OCURRENCE EVEN NO. OF TIMES(Maximum for longest) AND SET ITS FREQ TO ZERO
                    hashmap[s[i]]=0
                    #print maxodd
            return maxlen+maxodd        
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.