The description of the problem
You have a large text file containing words.
Given any two different words, find the shortest distance (in terms of number of words) between them in the file.
If the operation will be repeated many times for the same file (but different pairs of words), can you optimize your solution?
an example
Input: words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
Output: 1
The codes to address the above problem
#include <vector>
#include <string>
#include <iostream>
#include <climits>
using namespace std;
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int min_distance = INT_MAX;
vector<int> word1_index;
vector<int> word2_index;
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1) {
word1_index.emplace_back(i);
}
if (words[i] == word2) {
word2_index.emplace_back(i);
}
}
for (int i = 0; i < word1_index.size(); ++i) {
for (int j = 0; j < word2_index.size(); ++j) {
int distance = abs(word1_index[i] - word2_index[j]);
min_distance = min(min_distance, distance);
}
}
return min_distance;
}
};
int main()
{
Solution s;
vector<string> words = {"practice", "makes", "perfect", "coding", "makes"};
cout << "The closest distance between two words is: " << s.findClosest(words, "coding", "practice") << endl;
return 0;
}
The corresponding results
$ ./example
The closest distance between two words is: 3