Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the WordDistance class:
WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.
classWordDistance { public: unordered_map<string, vector<int>> wordToIndexes; WordDistance(vector<string>& wordsDict) { int n = wordsDict.size(); for (int i = 0; i < n; i++) { wordToIndexes[wordsDict[i]].push_back(i); } }
intshortest(string word1, string word2){ auto v1 = wordToIndexes[word1]; auto v2 = wordToIndexes[word2]; int idx1 = 0, idx2 = 0, n1 = v1.size(), n2 = v2.size(); int res = INT_MAX; while (idx1 < n1 && idx2 < n2) { res = min(res, abs(v1[idx1] - v2[idx2])); if (v1[idx1] < v2[idx2]) { idx1++; } else { idx2++; } } return res; } };
/** * Your WordDistance object will be instantiated and called as such: * WordDistance* obj = new WordDistance(wordsDict); * int param_1 = obj->shortest(word1,word2); */