gold-17-11


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

示例:

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

提示:

  • words.length <= 100000
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        List<Integer> index1 = new ArrayList<>();
        List<Integer> index2 = new ArrayList<>();

        if (word1.equals(word2)) {
            return 0;
        }

        for (int i = 0; i < words.length; i++) {
            if (words[i] != null && words[i].equals(word1)) {
                index1.add(i);
            }
            if (words[i] != null && words[i].equals(word2)) {
                index2.add(i);
            }
        }

        int result = Integer.MAX_VALUE;

        int i1 = 0;
        int i2 = 0;
        while (i1 < index1.size() && i2 < index2.size()) {
            int v1 = index1.get(i1);
            int v2 = index2.get(i2);
            int dis = getDis(v1, v2);

            if (dis < result) {
                result = dis;
            }
            if (v1 < v2) {
                i1++;
            } else {
                i2++;
            }
        }

        return result;
    }

    private int getDis(int i1, int i2) {
        return i1 > i2 ? i1 - i2 : i2 - i1;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !