Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “coding”
, word2 = “practice”
, return 3.
Given word1 = "makes"
, word2 = "coding"
, return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
根据题意,就是很简单的求两个字符的index的差值。一开始想的比简单还简单,直接loop了一遍,没考虑会出现重复字符的情况。然后补完提纯,用更加python的方法写了下面的代码块。
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
w1 = [i for i in xrange(len(words)) if words[i] == word1]
w2 = [i for i in xrange(len(words)) if words[i] == word2]
return min([abs(i - j) for i in w1 for j in w2])
代码的意思就是求出所有的出现的index,然后求两个list中数字的最小差值。
具体来说,应该是分两步走。
首先loop一遍,求出word1的index。
然后,对于某一个word2的index,对应所有word1的index进行差值比较。
等于说loop了两遍。这是我感觉最直接的方法。
提高一点的loop了一遍的方法
def shortestDistance(self, words, word1, word2):
size = len(words)
index1, index2 = size, size
ans = size
for i in xrange(size):
if words[i] == word1:
index1 = i
ans = min(ans, abs(index1-index2))
elif words[i] == word2:
index2 = i
ans = min(ans, abs(index1-index2))
return ans
loop的同时,一起查询word1和word2。查到index就及时进行比较,然后记录差值。