Python 56 ms easy to understand solution


  • 0
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            found = False
            curDis = -1
            minDis = -1
            first, second = '', ''
            for word in words:
    
                if not found and (word == word1 or word == word2):
                    found = True
                    curDis = 0
                    if word == word1:
                        first = word1
                        second = word2
                    else:
                        first = word2
                        second = word1
                
                elif found:
                    if word == first:
                        curDis = 0
                    elif word == second:
                        if curDis < minDis or minDis == -1:
                            minDis = curDis
                        #swap first and second
                        tmp = first
                        first = second
                        second = tmp
                        curDis = 0
                
                curDis += 1
            return minDis
    

    The idea:
    Until word1 or word2 is found, just proceed. Once it's found, count the step until another is found.
    If the same word found twice before another one found, because we have to detect the shortest distance, forget about the first one.


Log in to reply
 

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