Python Solution O(N) Single Pass


  • 0
    A

    Longest palindrome in a single pass using a single counter/char list

    def longestPalindrome(self, s):
            counter = 0
            count = [0] * 52
            for char in s:
                if ord(char) >= ord('a') and ord(char) <= ord('z'):
                    tempOrd = ord(char) - ord('a')
                else:
                    tempOrd = ord(char) - ord('A') + 25
                count[tempOrd] += 1
                if count[tempOrd] % 2 == 0:
                    counter += 2
                    
            if len(s) == counter:
                return counter
            else:
                return counter + 1

Log in to reply
 

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