Shortest Word Distance
这道题最好的办法肯定是交替变换两个词最近出现的位置然后算这些距离的大小了,不过也可以用哈希表记录位置之后再一个个比对,但是肯定没有这种一遍循环的方式好
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
aIndex, bIndex = -1, -1
result = sys.maxint
for index, word in enumerate(words):
if word == word1:
aIndex = index
if word == word2:
bIndex = index
if aIndex >= 0 and bIndex >= 0:
result = min(abs(aIndex - bIndex), result)
return result
Shortest Word Distance III
这道题如果想两种情况一起处理的逻辑不太好想,分开做倒不是很难
class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
if word1 == word2:
indexList = [i for i in xrange(len(words)) if words[i] == word1]
return min([indexList[i] - indexList[i - 1] for i in xrange(1, len(indexList))])
aIndex, bIndex = -1, -1
result = sys.maxint
for index, word in enumerate(words):
if word == word1:
aIndex = index
if word == word2:
bIndex = index
if aIndex >= 0 and bIndex >= 0:
result = min(abs(aIndex - bIndex), result)
return result
合在一起的不太好理解,以后有空再研究*