zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    树链剖分 关于点权与边权的转换
    2018 CCPC 吉林站 H Lovers || HDU 6562 (线段树哦)
    统计学习方法(一)概念
    python学习心得(三)
    python学习心得
    Python学习:基本概念
    Python学习(一)
    SparkMLlib聚类学习之KMeans聚类
    SparkMLlib回归算法之决策树
    SparkMLlib学习之线性回归
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12590515.html
Copyright © 2011-2022 走看看