Shortest Word Distance 解答

时间:2023-03-09 13:00:49
Shortest Word Distance 解答

Question

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.

Solution

双指针的方法。last_word1为word1最后一次出现的坐标。last_word2为word2最后一次出现的坐标。所以当last_word1变化时,我们计算last_word1 - last_word2 + 1,并且和当前最小值比较更新。Same to last_word2.

 class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
last_word1 = -1
last_word2 = -1
length = len(words)
result = length
for i in range(length):
if words[i] == word1:
last_word1 = i
if last_word2 != -1:
result = min(result, last_word1 - last_word2)
elif words[i] == word2:
last_word2 = i
if last_word1 != -1:
result = min(result, last_word2 - last_word1)
return result