Python solution with list


  • 0
    J
    class Solution(object):
        def longestPalindrome(self, s):
            lit = []
            count = 0
            for i in s:
                if i not in lit:
                    lit.append(i)
                else:
                    count+=1
                    lit.remove(i)
            return 1+count*2 if len(lit)>0  else count*2
    

    The Time complexity should be O(N).

    1. The For loop check every char.
    2. If char is exist in list then remove the char from list and increment "count" by 1.
    3. Else if char is not exist in list then add it into list.
    4. After the for loop, if list still have elements in it, which mean there exist char with odd number of count. So we will add 1 to the final ans.
    5. The final answer will be "count" * 2 + step 4

  • 0
    R

    You are using list, not dictionary. Why your title is "with hash table"?


  • 0
    J

    @ree975 sorry, I changed it


  • 0
    W

    Why don't you use set? Same idea but much easier


  • 0
    J

    @Wufan I did not think of using set. This solution just came out of my head first.


Log in to reply
 

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