Shortest Word Distance
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.
public int shortestDistance(String[] words, String word1, String word2) {
int dis = 1234567, w1 = -32767, w2 = 32767;
for(int i = 0 ; i < words.length; i ++){
if(words[i].equals(word1)) w1 = i;
else if(words[i].equals(word2)) w2 = i;
dis = Math.min(Math.abs(w1 - w2), dis);
}
return dis;
}
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
p1 = p2 = float('inf')
result = float('inf')
if word1 != word2:
for i, w in enumerate(words):
if w == word1:
p1 = i
elif w == word2:
p2 = i
result = min(abs(p2 - p1), result)
else:
for i, w in enumerate(words):
if w == word1:
p2 = p1
p1 = i
result = min(abs(p2 - p1), result)
return result