要求
请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。
示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
核心代码
class WordDistance:
def __init__(self, wordsDict: List[str]):
from collections import defaultdict
self.words = wordsDict
self.record = defaultdict(list)
for i,word in enumerate(self.words):
self.record[word].append(i)
def shortest(self, word1: str, word2: str) -> int:
res = len(self.words)
for pos1 in self.record[word1]:
for pos2 in self.record[word2]:
res = min(res,abs(pos1 - pos2))
return res
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
另一解法
class WordDistance:
def __init__(self, wordsDict: List[str]):
from collections import defaultdict
self.words = wordsDict
self.record = defaultdict(list)
for i,word in enumerate(self.words):
self.record[word].append(i)
def shortest(self, word1: str, word2: str) -> int:
res = float("inf")
p1,p2 = 0,0
while p1 < len(self.record[word1]) and p2 < len(self.record[word2]):
res = min(res,abs(self.record[word1][p1] - self.record[word2][p2]))
if self.record[word1][p1] < self.record[word2][p2]:
p1 += 1
else:
p2 += 1
return res
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
解题思路:第一种方案:我们使用一个字典用,键是单词,值是位置的列表,当我们查找两个单词的最小值的时候,我们使用一个历史最佳来存储两个单词中间的位置差的最小值。第二种解法:我们使用双指针法改进的版本:可以把时间复杂度从O(MN)加快到O(M + N),每次只让下标较小的那个指针往前进一步。