代码拉取完成,页面将自动刷新
# Time: O(n)
# Space: O(1)
class Solution:
# @param {string[]} words
# @param {string} word1
# @param {string} word2
# @return {integer}
def shortestWordDistance(self, words, word1, word2):
dist = float("inf")
is_same = (word1 == word2)
i, index1, index2 = 0, None, None
while i < len(words):
if words[i] == word1:
if is_same and index1 is not None:
dist = min(dist, abs(index1 - i))
index1 = i
elif words[i] == word2:
index2 = i
if index1 is not None and index2 is not None:
dist = min(dist, abs(index1 - index2))
i += 1
return dist
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。