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.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Input: word1 =“coding”
, word2 =“practice”
Output: 3
Input: word1 ="makes"
, word2 ="coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Companies:
LinkedIn
Related Topics:
Hash Table, Design
Similar Questions:
// OJ: https://leetcode.com/problems/shortest-word-distance-ii/
// Author: github.com/lzl124631x
// Time:
// * WordDistance: O(N)
// * shortest: O(N)
// Space: O(N)
class WordDistance {
private:
unordered_map<string, vector<int>> m;
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) {
auto &a = m[word1], &b = m[word2];
int i = 0, j = 0, dist = INT_MAX;
while (i < a.size() && j < b.size() && dist > 1) {
dist = min(dist, abs(a[i] - b[j]));
if (a[i] > b[j]) ++j;
else ++i;
}
return dist;
}
};