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.
OR
You have a large text file containing words. Given any two words, find the shortest distance (in terms of number of words) between them in the file. Can you make the searching operation in O(1) time? What about the space complexity for your solution?
OR
Find the minimum distance between 2 numbers in the array?
Input: file ="as was is the as the yahoo you me was the and", word =["the","was"]Output: 0Explanation: As was is the "as the yahoo you me **was** **the** and"
Example 2:
1
2
3
Input: file ="as was is the as the yahoo you me was the and", words =["you","the"]Output: 2Explanation: (as was is the as **the** yahoo **you** me was the and)
publicclassSolution {
publicintshortestDistance(String[] wordsDict, String word1, String word2) {
int p1 =-1, p2 =-1, min = Integer.MAX_VALUE;
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
p1 = i;
}
if (wordsDict[i].equals(word2)) {
p2 = i;
}
if (p1 !=-1 && p2 !=-1) {
min = Math.min(min, Math.abs(p1 - p2));
}
}
return min;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defshortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
p1: int =-1 p2: int =-1 min_distance: int = float("inf")
for i, word in enumerate(wordsDict):
if word == word1:
p1 = i
if word == word2:
p2 = i
if p1 !=-1and p2 !=-1:
min_distance = min(min_distance, abs(p1 - p2))
return min_distance