Skip to content

Latest commit

 

History

History
113 lines (87 loc) · 3.26 KB

File metadata and controls

113 lines (87 loc) · 3.26 KB

English Version

题目描述

给定一个字符串数组 wordsDict 和两个字符串 word1word2 ,返回列表中这两个单词之间的最短距离。

注意:word1word2 是有可能相同的,并且它们将分别表示为列表中 两个独立的单词

 

示例 1:

输入:wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
输出:1

示例 2:

输入:wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
输出:3

 

提示:

  • 1 <= wordsDict.length <= 105
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] 由小写英文字母组成
  • word1word2 都在 wordsDict

解法

Python3

class Solution:
    def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        i1 = i2 = -1
        shortest_distance = len(wordsDict)
        same = word1 == word2
        for i in range(len(wordsDict)):
            if same:
                if word1 == wordsDict[i]:
                    if i1 != -1:
                        shortest_distance = min(shortest_distance, i - i1)
                    i1 = i
            else:
                if word1 == wordsDict[i]:
                    i1 = i
                if word2 == wordsDict[i]:
                    i2 = i
                if i1 != -1 and i2 != -1:
                    shortest_distance = min(shortest_distance, abs(i1 - i2))
        return shortest_distance

Java

class Solution {
    public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
        int i1 = -1, i2 = -1;
        int shortestDistance = wordsDict.length;
        boolean same = word1.equals(word2);
        for (int i = 0; i < wordsDict.length; ++i) {
            if (same) {
                if (word1.equals(wordsDict[i])) {
                    if (i1 != -1) {
                        shortestDistance = Math.min(shortestDistance, i - i1);
                    }
                    i1 = i;
                }
            } else {
                if (word1.equals(wordsDict[i])) {
                    i1 = i;
                }
                if (word2.equals(wordsDict[i])) {
                    i2 = i;
                }
                if (i1 != -1 && i2 != -1) {
                    shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2));
                }
            }
        }
        return shortestDistance;
    }
}

...