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.

 1 class Solution(object):
 2     def shortestDistance(self, words, word1, word2):
 3         """
 4         :type words: List[str]
 5         :type word1: str
 6         :type word2: str
 7         :rtype: int
 8         """
 9         last_word1 = -1
10         last_word2 = -1
11         length = len(words)
12         result = length
13         for i in range(length):
14             if words[i] == word1:
15                 last_word1 = i
16                 if last_word2 != -1:
17                     result = min(result, last_word1 - last_word2)
18             elif words[i] == word2:
19                 last_word2 = i
20                 if last_word1 != -1:
21                     result = min(result, last_word2 - last_word1)
22         return result

 

posted @ 2015-11-04 09:21  树獭君  阅读(179)  评论(0编辑  收藏  举报