Leetcode: Shortest Word Distance

Question

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].

Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = “makes”, word2 = “coding”, return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Hide Tags Array
Hide Similar Problems (M) Shortest Word Distance II (M) Shortest Word Distance III

Solution

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

        l1, l2 = -1, -1
        res = len(words)
        for ind,elem in enumerate(words):
            if elem==word1:
                l1 = ind
                if l2>-1:
                    res = min(res, abs(l1-l2))
            if elem==word2:
                l2 = ind
                if l1>-1:
                    res = min(res, abs(l1-l2))

        return res 

你可能感兴趣的:(Leetcode: Shortest Word Distance)