Shortest Word Distance 3

题目描述

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

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

word1 and word2 may be the same and they represent two individual words in the list.

解题方法

就是多一个word1 == word2时候的查找

Solution

class Solution(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        dic = {}
        for idx, word in enumerate(words):
            if word in dic:
                dic[word].append(idx)
            else:
                dic[word] = [idx]


        if word1 == word2:
            list1 = dic[word1]
            minDis = sys.maxint
            for i in range(1, len(list1)):
                diff = list1[i] - list1[i-1]
                minDis = diff if minDis > diff else minDis

            return minDis

        list1 = dic[word1]
        list2 = dic[word2]

        p1, p2 = 0, 0
        minDis = sys.maxint
        while p1 < len(list1) and p2 < len(list2):
            diff = abs(list1[p1] - list2[p2])
            minDis = minDis if minDis < diff else diff
            if list1[p1] < list2[p2]:
                p1 += 1
            else:
                p2 += 1

        return minDis

Reference