面试题 17.11. 单词距离

    科技2024-10-13  18

    有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

    示例:

    输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" 输出:1

    1.抽出w1和w2遍历所有组合

    2.有点贪心的感觉

    class Solution: def findClosest(self, words: List[str], word1: str, word2: str) -> int: idx1, idx2 = float("-inf"), float("inf") res = len(words) for idx, word in enumerate(words): if word == word1: idx1 = idx elif word == word2: idx2 = idx res = min(res, abs(idx1-idx2)) return res

     

    Processed: 0.032, SQL: 8