Skip to content

Latest commit

 

History

History
62 lines (48 loc) · 1.76 KB

245. Shortest-Word-Distance-III.md

File metadata and controls

62 lines (48 loc) · 1.76 KB

Description

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.

Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

Note: You may assume word1 and word2 are both in the list.


这道题相对于编号243,允许两个单词相等,所以我们的代码只需要在前面基础上加上处理两个单词相等的情况即可。

python solution

class Solution:
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        if word1 == word2:  # 两个单词相等的情况
            wordIndex, res = -1, len(words)
            for i, v in enumerate(words):
                if v == word1: 
                    if wordIndex > -1:
                        res = min(res, i - wordIndex)
                    wordIndex = i
            return res
        
        # 两个单词不相等的情况
        word1Index, word2Index = -1, -1
        res = len(words)
        for i, v in enumerate(words):
            if v == word1:
                word1Index = i
                if word2Index > -1:  # 确保word2在之前已经出现过
                    res = min(res, i - word2Index)
            elif v == word2:
                word2Index = i
                if word1Index > -1:   # 确保word1在之前已经出现过
                    res = min(res, i - word1Index)
        return res
  • 时间复杂度:O(n)