Shortest Word Distance


  • 0

    Click here to see the full article post


  • 0
    J

    There an error for the one pass solution minDistance = Math.min(minDistance, Math.abs(i1 - i1)); have to be minDistance = Math.min(minDistance, Math.abs(i1 - i2));


  • 0

    Thanks! I have corrected it.


  • 0
    N

    You do not need currentDistance here.


  • 0
    W

    Check words[i] is word1 or word2, else continue. This can save a little.


  • 0
    class Solution(object):
        def shortestDistanceBF(self, words, word1, word2):
            """
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            """
            min_dist = len(words)
            for i in xrange(len(words)):
                if words[i] == word1:
                    for j in xrange(len(words)):
                        if words[j] == word2:
                            min_dist = min(min_dist, abs(i-j))
            return min_dist
    
        def shortestDistance(self, words, word1, word2):
            i1, i2 = -1, -1
            min_dist = len(words)
            for i in xrange(len(words)):
                if words[i] == word1:
                    i1 = i
                elif words[i] == word2:
                    i2 = i
                if i1 != -1 and i2 != -1:
                    min_dist = min(min_dist, abs(i1-i2))
            return min_dist
    

Log in to reply
 

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