请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-word-distance-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
如果每次调用都暴力搜索是不行滴,因为最后一个TEST CASE会调用很多很多次,会超时。
所以可以考虑初始化时建立hashmap, key是words里的每个单词,val是每个word出现的所有下标,
这样调用shortest的时候,就只需要处理hashmap中word1和word2的记录即可。
class WordDistance(object):
def __init__(self, words):
"""
:type words: List[str]
"""
from collections import defaultdict
self.words = words
self.record = defaultdict(list)
for i, word in enumerate(words):
self.record[word].append(i)
# print self.record
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: 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
第二种思路:
下面是用双指针法改进的版本:
可以把时间复杂度从O(MN)加快到O(M + N),
每次只让下标较小的那个指针往前进一步。
class WordDistance(object):
def __init__(self, words):
"""
:type words: List[str]
"""
self.record = collections.defaultdict(list)
for i, word in enumerate(words):
self.record[word].append(i)
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: 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