Leetcode 刷题 - 243 - 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.


根据题意,就是很简单的求两个字符的index的差值。一开始想的比简单还简单,直接loop了一遍,没考虑会出现重复字符的情况。然后补完提纯,用更加python的方法写了下面的代码块。

class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        w1 = [i for i in xrange(len(words)) if words[i] == word1]
        w2 = [i for i in xrange(len(words)) if words[i] == word2]

        return min([abs(i - j) for i in w1 for j in w2])

代码的意思就是求出所有的出现的index,然后求两个list中数字的最小差值。


具体来说,应该是分两步走。

首先loop一遍,求出word1的index。

然后,对于某一个word2的index,对应所有word1的index进行差值比较。

等于说loop了两遍。这是我感觉最直接的方法。


提高一点的loop了一遍的方法

def shortestDistance(self, words, word1, word2):
    size = len(words)
    index1, index2 = size, size
    ans = size

    for i in xrange(size):
        if words[i] == word1:
            index1 = i
            ans = min(ans, abs(index1-index2))
        elif words[i] == word2:
            index2 = i
            ans = min(ans, abs(index1-index2))
    return ans

loop的同时,一起查询word1和word2。查到index就及时进行比较,然后记录差值。





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值