面试题 17.11
You have a large text file containing words. Given any two 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?
Example:
Input: words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" Output: 1 Note:
words.length <= 100000
Solutions
two pointers O(n)
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int index1 = -0x3f3f3f3f, index2 = -0x3f3f3f3f;
int res = INT_MAX;
for (int i = 0; i < words.size(); i++) {
if (words[i] == word1) {
index1 = i;
res = min(res, index1 - index2);
}
else if (words[i] == word2) {
index2 = i;
res = min(res, index2 - index1);
}
}
return res;
}
};preprocess with hash map
Suits for the follow up problem.
Last updated
Was this helpful?