# 244. Shortest Word Distance II - CPP - Solution

• ``````// 244. Shortest Word Distance II
// https://leetcode.com/problems/shortest-word-distance-ii/
#include <iostream>
#include <algorithm> // required for min() function
#include <cstdlib> // required for abs() function
#include <vector> // required for vector container
#include <string> // required for string container
#include <unordered_map> // required for unordered_map container
using namespace std;
class WordDistance {
public:
WordDistance(const vector<string>& words) {
for (size_t i = 0; i < words.size(); ++i) {
this->str2vec[words[i]].push_back(i);
}
}
int shortest(const string& word1, const string& word2) {
int result = 0;
for (size_t i = 0; i < this->str2vec[word1].size(); ++i) {
for (size_t j = 0; j < this->str2vec[word2].size(); ++j) {
if (!i && !j) {
result = abs(this->str2vec[word1][i] - this->str2vec[word2][j]);
}
else if (i || j) {
result = min(result, abs(this->str2vec[word1][i] - this->str2vec[word2][j]));
}
}
}
return result;
}
private:
unordered_map<string, vector<int>> str2vec;
};
int main(int argc, const char** argv) {
vector<string> words = {"practice", "makes", "perfect", "coding", "makes"};
WordDistance wordDistance(words);
cout << wordDistance.shortest("coding", "practice") << '\n';
getchar();
return 0;
}

// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.