leetcode_243 最短单词距离

96 阅读1分钟

要求

给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。

示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"]

输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1

注意: 你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。

核心代码

class Solution:
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        res = len(wordsDict)
        post1,post2 = -res,-res
        for index,word in enumerate(wordsDict):
            if word == word1:
                post1 = index
            elif word == word2:
                post2 = index
            else:
                continue
            res = min(res,abs(post1 - post2))
        return res

image.png

解题思路:就是循环找到两个词的位置,然后保存一个历史最佳,比较简单。