Skip to content

Commit d505a98

Browse files
authored
Create Shortest Word Distance II.py
1 parent 95ab7ba commit d505a98

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Shortest Word Distance II.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.
3+
4+
Example:
5+
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
6+
7+
Input: word1 = “coding”, word2 = “practice”
8+
Output: 3
9+
10+
Input: word1 = "makes", word2 = "coding"
11+
Output: 1
12+
13+
Note:
14+
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
15+
16+
'''
17+
18+
class WordDistance(object):
19+
20+
def __init__(self, words):
21+
"""
22+
:type words: List[str]
23+
"""
24+
25+
self.word_to_idx = {}
26+
for i in xrange(len(words)):
27+
if words[i] in self.word_to_idx:
28+
self.word_to_idx[words[i]].append(i)
29+
else:
30+
self.word_to_idx[words[i]] = [i]
31+
32+
self.memory = {}
33+
34+
def shortest(self, word1, word2):
35+
"""
36+
:type word1: str
37+
:type word2: str
38+
:rtype: int
39+
"""
40+
41+
if (word1, word2) in self.memory:
42+
return self.memory[(word1, word2)]
43+
if (word2, word1) in self.memory:
44+
return self.memory[(word2, word1)]
45+
46+
if word1 not in self.word_to_idx or word2 not in self.word_to_idx:
47+
return -1
48+
49+
if word1 == word2:
50+
return 0
51+
52+
i = 0
53+
j = 0
54+
res = float('inf')
55+
while i < len(self.word_to_idx[word1]) and j < len(self.word_to_idx[word2]):
56+
if self.word_to_idx[word1][i] < self.word_to_idx[word2][j]:
57+
res = min(res, self.word_to_idx[word2][j] - self.word_to_idx[word1][i])
58+
i += 1
59+
elif self.word_to_idx[word1][i] == self.word_to_idx[word2][j]:
60+
res = min(res, 0)
61+
break
62+
else:
63+
res = min(res, self.word_to_idx[word1][i] - self.word_to_idx[word2][j])
64+
j += 1
65+
66+
self.memory[(word1, word2)] = res
67+
68+
return res
69+
70+
# Your WordDistance object will be instantiated and called as such:
71+
# obj = WordDistance(words)
72+
# param_1 = obj.shortest(word1,word2)

0 commit comments

Comments
 (0)