class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
}
};
面试题 17.11. 单词距离
有个内含单词的超大文本文件,给定任意两个不同的
单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
示例:
输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" 输出:1
提示:
words.length <= 100000
原站题解
python3 解法, 执行用时: 132 ms, 内存消耗: 30.8 MB, 提交时间: 2022-05-27 15:17:18
class Solution: def findClosest(self, words: List[str], word1: str, word2: str) -> int: ans = len(words) index1, index2 = -1, -1 for i, word in enumerate(words): if word == word1: index1 = i if word == word2: index2 = i if index1 >= 0 and index2 >= 0: ans = min(abs(index1-index2), ans) return ans