forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
33 lines (26 loc) · 870 Bytes
/
Solution.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
/**
* @author Oleg Cherednik
* @since 28.02.2019
*/
public class Solution {
public static void main(String[] args) {
System.out.println(getMinDistance("dog cat hello cat dog dog hello cat world", "hello", "world")); // 1
}
public static int getMinDistance(String str, String one, String two) {
String[] words = str.split("\\s+");
int posOne = -1;
int posTwo = -1;
int res = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(one))
posOne = i;
else if (words[i].equals(two))
posTwo = i;
else
continue;
if (posOne != -1 && posTwo != -1)
res = Math.min(res, Math.abs(posTwo - posOne) - 1);
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}