This was a follow up of shortest Word Distance. The only difference was now given the list of words and your method would be called repeatedly many times W ith different parameters. How would optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes both words word1 and Word2 and return the shortest distance between these, words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “coding”
, word2 = “practice”
, return 3.
Given word1 = "makes"
, word2 = "coding"
, return 1.
Note:
Assume that word1 does not equal to word2, and Word1 and Word2 is both in The list.
243. Shortest word Distance, the difference is that this time requires multiple calls to find the shortest word distance function.
Python:
# Time: init:o (N), Lookup:o (A + B), A, B is occurences of word1, word2# space:o (n) Import Collectionsclass Worddista NCE: # 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
C++:
Class Worddistance {public: worddistance (vector<string>& words) {for (int i = 0; i < words.size (); + +i) { m[words[i]].push_back (i); } } int shortest (string word1, String word2) { int res = Int_max; for (int i = 0; i < m[word1].size (); ++i) {for (int j = 0; J < m[word2].size (); ++j) { res = min (res, ABS (M [Word1] [i]-m[word2][j])); } } return res; } Private: unordered_map<string, vector<int> > m;};
C++:
Class Worddistance {public: worddistance (vector<string>& words) {for (int i = 0; i < words.size (); + +i) { m[words[i]].push_back (i); } } int shortest (string word1, String word2) { int i = 0, j = 0, res = Int_max; while (I < M[word1].size () && J < M[word2].size ()) { res = min (res, ABS (m[word1][i)-m[word2][j]);
m[word1][i] < M[word2][j]? ++i: ++j; } return res; } Private: unordered_map<string, vector<int> > m;};
Similar topics:
[Leetcode] 243. Shortest word Distance shortest word distance
[Leetcode] 245. Shortest word Distance III shortest word Distance III
[Leetcode] 244. Shortest word Distance II shortest word Distance II