<![CDATA[Python solution with comments.]]>def shortestWordDistance(self, words, word1, word2):
p1 = p2 = -1
res = len(words)
# first case: the same as Shortest Word Distance
if word1 != word2:
for i, w in enumerate(words):
if w == word1:
p1 = i
if w == word2:
p2 = i
if p1 > -1 and p2 > -1:
res = min(res, abs(p1-p2))
return res
else:
# pre and i record previous and current word1 respectively
pre, i = -len(words), 0
while i < len(words):
while i < len(words) and words[i] != word1:
i += 1
if i < len(words):
res = min(res, i-pre)
pre = i
i += 1
return res
]]>https://discuss.leetcode.com/topic/21855/python-solution-with-commentsRSS for NodeThu, 22 Feb 2018 17:10:35 GMTWed, 19 Aug 2015 08:44:38 GMT60<![CDATA[Reply to Python solution with comments. on Wed, 19 Aug 2015 08:44:38 GMT]]>def shortestWordDistance(self, words, word1, word2):
p1 = p2 = -1
res = len(words)
# first case: the same as Shortest Word Distance
if word1 != word2:
for i, w in enumerate(words):
if w == word1:
p1 = i
if w == word2:
p2 = i
if p1 > -1 and p2 > -1:
res = min(res, abs(p1-p2))
return res
else:
# pre and i record previous and current word1 respectively
pre, i = -len(words), 0
while i < len(words):
while i < len(words) and words[i] != word1:
i += 1
if i < len(words):
res = min(res, i-pre)
pre = i
i += 1
return res
]]>https://discuss.leetcode.com/post/23540https://discuss.leetcode.com/post/23540Wed, 19 Aug 2015 08:44:38 GMT