Description
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = “makes”, word2 = “coding”, return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Two Pointers
Use a “prev” pointer to track the previous matching word.
The trick is to set the prev to “-1” value.
We move forward the cur pointer.
Whenever the cur word matches word1 or word2, we check whether it is different from the previous word, if yes, we calculate the distance and set prev to cur. If no, we only set prev to cur.
/**
* @time complexity: O(n)
* @runtime: 2ms
*/
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int ret = Integer.MAX_VALUE, prev = -1;
for (int i=0; i<words.length; i++) {
if (words[i].equals(word1) || words[i].equals(word2)) {
if (prev >= 0 && !words[i].equals(words[prev])) {
ret = Math.min(ret, i-prev);
}
prev = i;
}
}
return ret;
}
}
Runtime: 2ms