搜索
您的当前位置:首页正文

力扣 面试题 17.11. 单词距离

来源:意榕旅游网
题目

有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

示例

输入:words = [“I”,“am”,“a”,“student”,“from”,“a”,“university”,“in”,“a”,“city”], word1 = “a”, word2 = “student”
输出:1

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-closest-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1:双指针
Java实现
class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        int n = words.length;
        int idx1 = -1, idx2 = -1;
        int ans = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            if (words[i].equals(word1)) {
                idx1 = i;
            } else if (words[i].equals(word2)) {
                idx2 = i;
            }
            
            if (idx1 != -1 && idx2 != -1) {
                ans = Math.min(ans, Math.abs(idx1 - idx2));
            }
        }
        return ans;
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top