244. Shortest Word Distance II
Input: word1 = “coding”, word2 = “practice”
Output: 3Input: word1 = "makes", word2 = "coding"
Output: 1// 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;
};Last updated