面试题 17.11. 单词距离https://leetcode.cn/problems/find-closest-lcci/
有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-closest-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
简单模拟即可
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int l = words.size();
int ans = l;
int index1 = -1;
int index2 = -1;
for (int i = 0; i < l; i++)
{
if (word1 == words[i])
index1 = i;
else if (word2 == words[i])
index2 = i;
if (index1 >= 0 && index2 >= 0)
ans = min(ans, abs(index1 - index2));
}
return ans;
}
};