# 245. Shortest Word Distance III - CPP - Solution

• ``````// 245. Shortest Word Distance III
// https://leetcode.com/problems/shortest-word-distance-iii/
#include <iostream>
#include <cstdlib> // required for abs() function
#include <vector> // required for vector container
#include <string> // required for string container
#include <algorithm> // required for min() function
#include <unordered_map> // required for unordered_map container
using namespace std;
class Solution {
public:
int shortestWordDistance(const vector<string>& words, const string& word1, const string& word2) {
int result = 0;
for (size_t i = 0; i < words.size(); ++i) {
this->str2vec[words[i]].push_back(i);
}
if (word1 == word2) {
for (size_t i = 0; i < this->str2vec[word1].size(); ++i) {
if (i == 0 || i == 1) {
result = abs(this->str2vec[word1][1] - this->str2vec[word1][0]);
}
else if (i >= 2) {
result = min(result, abs(this->str2vec[word1][i] - this->str2vec[word1][i - 1]));
}
}
}
else if (word1 != word2) {
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][0] - this->str2vec[word2][0]);
}
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) {
Solution solution;
vector<string> words = {"practice", "makes", "perfect", "coding", "makes"};
//string word1 = "makes", word2 = "coding";
string word1 = "makes", word2 = "makes";
cout << solution.shortestWordDistance(words, word1, word2) << '\n';
getchar();
return 0;
}``````

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