243. Shortest Word Distance

def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        length = len(words)
        idx1, idx2, res = -length, -length, length
        for i in xrange(length):
            if words[i] == word1:
                idx1 = i
            elif words[i] == word2:
                idx2 = i
            if idx1 >= 0 and idx2 >= 0:
                res = min(res, abs(idx1 - idx2))
        return res

244. Shortest Word Distance II

class WordDistance(object):

    def __init__(self, words):
        """
        :type words: List[str]
        """
        self.d = collections.defaultdict(list)
        for i, w in enumerate(words):
            self.d[w].append(i)

    def shortest(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        res = float('inf')
        d1, d2, i, j = self.d[word1], self.d[word2], 0, 0
        while i < len(d1) and j < len(d2):
            res = min(res, abs(d1[i] - d2[j]))
            if d1[i] < d2[j]:
                i += 1
            else:
                j += 1
        return res

245. Shortest Word Distance III

def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        length = len(words)
        idx1, idx2, res, same = -1, -1, float('inf'), word1 == word2
        for i in xrange(length):
            if words[i] == word1:
                if same:
                    idx2 = idx1
                    idx1 = i
                else:
                    idx1 = i
            elif words[i] == word2:
                idx2 = i
            if idx1 >= 0 and idx2 >= 0:
                res = min(res, abs(idx1 - idx2))
        return res

results matching ""

    No results matching ""