【EASY】Shortest Word Distance

# 问题

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

Example:

Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

``````Input: word1 = “coding”, word2 = “practice”
Output: 3``````
``````Input: word1 = "makes", word2 = "coding"
Output: 1``````

Note:

• You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

# 分析过程

• 输入：一个单词数组以及两个单词，这两个单词假定一定包含在数组内。
• 输出：这两个单词的最短距离。
• 思路：遍历数组，记录上次找到单词的索引，下次再找到时候做减法，见注释。

# 解决方法

``````class Solution {
func shortestDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
// 记录上次找到word1或者word2的索引
var lastIndex = -1
var result = Int.max

for (i, word) in words.enumerated() {
if word == word1 || word == word2 {
// 首次进入先赋值
guard lastIndex > -1 else {
lastIndex = i
continue
}
// 上次找到的是word1或word2
// 如果上次找了word1，这次找到的还是word1，不更新
if words[lastIndex] != word {
// 和上次找到的值做减法即可
result = min(result, i - lastIndex)
}
lastIndex = i
}
}

return result
}
}``````