1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
shortest-word-distance-ii.py 910 Bytes
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . update
# Time: init: O(n), lookup: O(a + b), a, b is occurences of word1, word2
# Space: O(n)
import collections
class WordDistance(object):
# 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 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助