题目描述
有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。
示例:
1 | 输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" |
题解
双指针
- 从前往后遍历字符串组
- 如果当前的字符串与word1相同, 更新当前索引index1; 如果当前的字符串与word2相同, 更新当前索引index2
- 若两个索引都不为初始值-1, 即都已成功定位, 则计算当前距离
1 | public int findClosest(String[] words, String word1, String word2) { |