-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordDistanceFinder.java
More file actions
34 lines (26 loc) · 968 Bytes
/
Copy pathWordDistanceFinder.java
File metadata and controls
34 lines (26 loc) · 968 Bytes
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
import java.util.StringTokenizer;
public class WordDistanceFinder {
public static void main(String args[]) {
String sample = "hello how are you how are hello you";
System.out.println(findMinDistance(sample, "hello", "you"));
}
private static int findMinDistance(String sample, String word1, String word2) {
StringTokenizer str = new StringTokenizer(sample, " ");
int minDiffDistance = Integer.MAX_VALUE;
int distance = 0;
while (str.hasMoreTokens()) {
String token = str.nextToken();
if (token.equals(word1)) {
distance = 0;
} else if (token.equals(word2)) {
minDiffDistance = Math.min(minDiffDistance, distance);
}
distance++;
}
if (minDiffDistance == Integer.MAX_VALUE || minDiffDistance == 0) {
return -1;
} else {
return minDiffDistance;
}
}
}