Python 4-line code using list comprehension


  • 0
    T

    class Solution(object):
    def shortestDistance(self, words, word1, word2):
    """
    :type words: List[str]
    :type word1: str
    :type word2: str
    :rtype: int
    """

        word1_index = [i for i in range(len(words)) if words[i]==word1]  #get all index for word1
        word2_index = [i for i in range(len(words)) if words[i]==word2]  #get all index for word2
        
        distance = [abs(i-j) for i in word1_index for j in word2_index ]  #get all differences
        return min(distance)

Log in to reply
 

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