给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
word1 和 word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"].
输入: word1 = “makes”, word2 = “coding”
输出: 1
输入: word1 = "makes", word2 = "makes"
输出: 3
注意:
你可以假设 word1 和 word2 都在列表里。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-word-distance-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
分类讨论,
如果word1!= word2那么和之前的题目一模一样,
如果相等,那么就用一个变量记录上一次出现的下表即可。
class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
res = len(words)
if word1 != word2:
pos1, pos2 = -1, -1
for i, word in enumerate(words):
if word == word1:
pos1 = i
elif word == word2:
pos2 = i
if pos2 != -1 and pos1 != -1:
res = min(res, abs(pos1 - pos2))
else:
pos = -1
for i, word in enumerate(words):
if word == word1:
if pos != -1:
# print i, pos
res = min(res, i - pos)
pos = i
return res