题目地址:
https://leetcode.com/problems/shortest-word-distance/
给定一个字符串列表,再给定其中的两个字符串,题目保证两个字符串不等。求这两个字符串在列表里出现的位置的最小下标差(也就是说列表里可能包含给定的字符串多次,要寻找下标差最小的两个)。
开两个指针,同时遍历数组,当遇到word1
或者word2
的时候更新指针,同时更新得到的最短距离。代码如下:
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int res = Integer.MAX_VALUE;
int idx1 = -1, idx2 = -1;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
idx1 = i;
}
if (words[i].equals(word2)) {
idx2 = i;
}
if (idx1 != -1 && idx2 != -1) {
res = Math.min(res, Math.abs(idx1 - idx2));
}
}
return res;
}
}
时间复杂度 O ( n l ) O(nl) O(nl)( n n n为列表里字符串个数, l l l为最长字符串长度)。
算法正确性证明:
假设两个字符串达到最短距离时出现的位置是
i
i
i和
j
j
j,那么可以知道
i
i
i和
j
j
j之间肯定不会出现那两个字符串的任意一个(否则就能得到更短的距离)。而算法是可以取到这两个位置的,所以算法正确。