Python 8 Lines Code ( Beating 94% )


  • 2
    R
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            """
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            """
            ret = len(words)
            index1 = [ x for x in range(len(words)) if words[x] == word1 ]
            index2 = [ x for x in range(len(words)) if words[x] == word2 ]
            
            for i in index1:
                for j in index2:
                    distance = abs(i - j)
                    if distance < ret: ret = distance
            
            return ret
    

Log in to reply
 

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