Python 100% recursive O(mn)


  • 0
    Y

    very surprised to beat 100%, surely many others have done the same before? are the timings correct?

        def minDistance(self, word1, word2):
            return self.edit_distance(word1, len(word1)-1, word2, len(word2)-1, {})
    
        def edit_distance(self, word1, i, word2, j, memo):      # i, j are next indices to be matched
            if i < 0 or j < 0:           # one string is empty (already matched), return remaining length of other
                return i + 1 + j + 1
    
            if (i, j) in memo:
                return memo[(i, j)]
    
            if word1[i] == word2[j]:
                result = self.edit_distance(word1, i-1, word2, j-1, memo)
            else:
                result = 1 + min(self.edit_distance(word1, i-1, word2, j, memo),
                                 self.edit_distance(word1, i, word2, j-1, memo),
                                 self.edit_distance(word1, i-1, word2, j-1, memo))
    
            memo[(i, j)] = result
            return result
    

Log in to reply
 

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