1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
shortest-word-distance-ii.py 881 Bytes
一键复制 编辑 原始数据 按行查看 历史
# Time: init: O(n), lookup: O(a + b), a, b is occurences of word1, word2
# Space: O(n)
class WordDistance:
# initialize your data structure here.
# @param {string[]} words
def __init__(self, words):
self.wordIndex = collections.defaultdict(list)
for i in xrange(len(words)):
self.wordIndex[words[i]].append(i)
# @param {string} word1
# @param {string} word2
# @return {integer}
# Adds a word into the data structure.
def shortest(self, word1, word2):
indexes1 = self.wordIndex[word1]
indexes2 = self.wordIndex[word2]
i, j, dist = 0, 0, float("inf")
while i < len(indexes1) and j < len(indexes2):
dist = min(dist, abs(indexes1[i] - indexes2[j]))
if indexes1[i] < indexes2[j]:
i += 1
else:
j += 1
return dist
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助