8-line python with comments

  • 0
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            prev = -1  # initially -1; supposed to always point to either word1 or word2
            minDistance = len(words)
            for i in range(0, len(words)):
                if words[i] in (word1, word2):
                    if prev != -1 and words[i] != words[prev]:  # time to update minDistance
                        minDistance = min(minDistance, i - prev)
                    prev = i  # as long as words[i] is word1 or word2, prev is updated anyway
            return minDistance

Log in to reply

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