【MEDIUM】Shortest Word Distance III

发布于: 2019-03-02 18:25
阅读: 38
评论: 0
喜欢: 0

问题

原题链接:https://leetcode.com/problems/shortest-word-distance-iii/

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

word1 and word2 may be the same and they represent two individual words in the list.

Example:

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

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

Note:

  • You may assume word1 and word2 are both in the list.

分析过程

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

解决方法

class Solution {
    func shortestWordDistance(_ 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,不更新
                // 但是如果word1和word2相同的话,也是可以更新的
                if word1 == word2 || words[lastIndex] != word {
                    // 和上次找到的值做减法即可
                    result = min(result, i - lastIndex)
                }
                lastIndex = i
            }
        }

        return result
    }
}

Thanks for reading.

All the best wishes for you! 💕