244. Shortest Word Distance II
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.
// Hash table
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) { // time: O(m * n); space: O(1)
int res = INT_MAX;
for (int idx1 : m[word1]) {
for (int idx2 : m[word2]) {
res = min(res, abs(idx1 - idx2));
}
}
return res;
}
private:
unordered_map<string, vector<int> > m;
};
// Hash table
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) { // time: O(m + n); space: O(1)
int res = INT_MAX, i = 0, j = 0;
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;
};
Last updated
Was this helpful?