因为LeetCode免费题目做完了,所以开始网上云做题(穷哭www)
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 =“coding”, word2 =“practice”
输出: 3
输入: word1 ="makes", word2 ="coding"
输出: 1
思路:用两个变量存储单词位置,遍历数组,更新单词位置和距离即可
class Solution(object):
def shortestDistance(self, words, word1, word2):
res = len(words)
a, b = -1, -1
for i, word in enumerate(words):
if word == word1:
a = i
if word == word2:
b = i
if a != -1 and b != -1:
res = min(res, abs(a - b))
return res