Given an array of strings wordsDict
and two different strings that already exist in the array word1
and word2
, return the shortest distance between these two words in the list.
Example 1:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3
Example 2:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" Output: 1
Constraints:
1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i]
consists of lowercase English letters.word1
andword2
are inwordsDict
.word1 != word2
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
i1 = i2 = -1
shortest_distance = len(wordsDict)
for i in range(len(wordsDict)):
if wordsDict[i] == word1:
i1 = i
elif wordsDict[i] == word2:
i2 = i
if i1 != -1 and i2 != -1:
shortest_distance = min(shortest_distance, abs(i1 - i2))
return shortest_distance
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int i1 = -1, i2 = -1;
int shortestDistance = wordsDict.length;
for (int i = 0; i < wordsDict.length; ++i) {
if (word1.equals(wordsDict[i])) {
i1 = i;
} else if (word2.equals(wordsDict[i])) {
i2 = i;
}
if (i1 != -1 && i2 != -1) {
shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2));
}
}
return shortestDistance;
}
}