-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path243ShortestWordDistance.java
More file actions
37 lines (32 loc) · 1.12 KB
/
243ShortestWordDistance.java
File metadata and controls
37 lines (32 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
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.
*/
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2)
{
int shortestDist = wordsDict.length;
int word1Index = -1;
int word2Index = -1;
for(int i = 0; i < wordsDict.length; i++)
{
if(wordsDict[i].equals(word1))
{
word1Index = i;
if(word2Index != -1 && (Math.abs(word1Index-word2Index) < shortestDist))
{
shortestDist = Math.abs(word1Index-word2Index);
}
}
else if(wordsDict[i].equals(word2))
{
word2Index = i;
if(word1Index != -1 && (Math.abs(word1Index-word2Index) < shortestDist))
{
shortestDist = Math.abs(word1Index-word2Index);
}
}
}
return shortestDist;
}
}