Leetcode 244 Solution
This article provides solution to leetcode question 244 (shortest-word-distance-ii)
Access this page by simply typing in "lcs 244" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/shortest-word-distance-ii
Solution
class WordDistance {
unordered_map<string, vector<int>> a;
public:
WordDistance(vector<string> words) {
for (int i = 0; i < words.size(); i++)
a[words[i]].push_back(i);
}
int shortest(string word1, string word2) {
auto& v1 = a[word1];
auto& v2 = a[word2];
int i1 = 0;
int i2 = 0;
int min_val = INT_MAX;
while (i1 < v1.size() && i2 < v2.size())
{
min_val = min(min_val, (int)abs(v1[i1] - v2[i2]));
if (v1[i1] > v2[i2])
i2++;
else
i1++;
}
return min_val;
}
};
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/