• 924. 单词最短距离


    924. 单词最短距离

    中文English

    给出一个单词列表和两个单词单词1,单词2,返回列表中这两个单词之间的最短距离。

    样例

    样例 1:

    输入:["practice", "makes", "perfect", "coding", "makes"],"coding","practice"
    输出:3
    解释:index("coding") - index("practice") = 3
    

    样例 2:

    输入:["practice", "makes", "perfect", "coding", "makes"],"makes","coding"
    输出:1
    解释:index("makes") - index("coding") = 1
    

    注意事项

    您可以假定单词1不等于单词2,而单词1和单词2在列表中都存在

    class Solution:
        """
        @param words: a list of words
        @param word1: a string
        @param word2: a string
        @return: the shortest distance between word1 and word2 in the list
        """
        '''
        1.word1和word2可能都存在多个的情况,所以需要两层循环,取出所有可能的距离。(取出列表全部重复元素的索引)
        2.初始化res,将两个单词距离全部append到res里面,返回最小值
        '''
        def shortestDistance(self,words,word1,word2):
            res = []
            l_word1 = [index for index,value in enumerate(words) if value == word1]
            l_word2 = [index for index,value in enumerate(words) if value == word2]
    
            #此时求出全部的距离,append到res里面
            for i in l_word1:
                for j in l_word2:
                    s = abs(i - j)
                    res.append(s)
            return min(res)

  • 相关阅读:
    jQuery 从无到有.一天完成.
    JavaScript从无到有(一天完成)
    HTML(第一篇)
    前端认识
    三元表达式,列表推导是,字典生成式
    ORM之youku项目小练习(上)
    高逼格壁纸
    pymysql 基操全套
    怎么学好编程?
    mysql 事务
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12590515.html
Copyright © 2020-2023  润新知