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)
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12590515.html
时间: 2024-10-07 23:34:01