One pointer Python solution, avoid duplicately calculating distance between two pointers

  • 0
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            start = -1
            result = 2**31 - 1
            for i, w in enumerate(words):
                if start > -1 and ((w == word1 and words[start] == word2) or\
                (w == word2 and words[start] == word1)):
                    result = min(result, i - start)
                if w == word1 or w == word2:
                    start = i
            return result

    Maybe others have similar solution. Just post for sharing. start points to last word1 or word2. Since I am not using two pointers, I avoided calculating distances between unchanged pointers, I guess.

Log in to reply

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