-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12_6.java
50 lines (41 loc) · 1.12 KB
/
day12_6.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
// Given a list of words followed by two words, the task to find the minimum distance between the given two words in the list of words
// Example 1:
// Input:
// S = { "the", "quick", "brown", "fox",
// "quick"}
// word1 = "the"
// word2 = "fox"
// Output: 3
// Explanation: Minimum distance between the
// words "the" and "fox" is 3
class Solution {
int shortestDistance(ArrayList<String> s, String word1, String word2) {
// code here
int word1_count =-1;
int word2_count =-1;
int dis = Integer.MAX_VALUE;
for(int i=0; i<s.size(); i++)
{
if(s.get(i).equals(word1))
{
word1_count=i;
}
if(s.get(i).equals(word2))
{
word2_count=i;
}
if(word1_count >=0 && word2_count>=0)
{
dis = Math.min(Math.abs(word2_count-word1_count),dis);
}
}
if(dis==Integer.MAX_VALUE)
{
return 0;
}
else
{
return dis;
}
}
};