[python]:单词距离

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

示例:

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

words.length <= 100000

一、双指针
在一个for循环里遍历word里每一个词,每遇到word1或者word2时,如果当前词与i的词不同就做差求距离,然后将i指向当前j的位置,然后继续向前遍历。

class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        i, ans = 0, len(words)
        for j, word in enumerate(words):
            if word == word1 or word == word2:
                if word != words[i] and (words[i] == word1 or words[i] == word2):
                    ans = min(ans, j-i)
                i = j
        return ans

二、字典
用数组记录两个词出现的位置,在找两个数组绝对值最小的差。

class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        p1 = []
        p2 = []
        for i in range(len(words)):
            if words[i] == word1:
                p1.append(i)
            if words[i] == word2:
                p2.append(i)
        diff = len(words)
        i, j = 0, 0
        while (i < len(p1)) and (j < len(p2)):
            if diff > abs(p1[i] - p2[j]):
                diff = abs(p1[i] - p2[j])
            if p1[i] > p2[j]:
                j += 1
            else:
                i += 1
        return diff
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值