[LeetCode] 244. Shortest Word Distance II 最短单词距离 II
16lz
2021-01-22
This is afollow upofShortest Word Distance. The only difference is now you are given the list of words and your method will be calledrepeatedlymany times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes two wordsword1andword2and return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"]
.
Givenword1=“coding”
,word2=“practice”
, return 3.
Givenword1="makes"
,word2="coding"
, return 1.
Note:
You may assume thatword1does not equal toword2, andword1andword2are both in the list.
243. Shortest Word Distance的拓展,不同的是这次需要多次调用求最短单词距离的函数。
Python:
# Time: init: O(n), lookup: O(a + b), a, b is occurences of word1, word2 # Space: O(n) import collections 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
更多相关文章
- Python基础数据类型-函数传参详解
- python1.返回一个字符串中出现次数第二多的单词 2.字符串中可能
- python函数不定长参数
- python基础(7)--深浅拷贝、函数
- Python中int()函数的用法
- python 函数式编程
- Python内置函数之匿名(lambda)函数
- python函数的属性
- python学习笔记10(函数一): 函数使用、调用、返回值