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

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4935017.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值