-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNearestRepeatEntries.java
More file actions
44 lines (39 loc) · 1.23 KB
/
NearestRepeatEntries.java
File metadata and controls
44 lines (39 loc) · 1.23 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
38
39
40
41
42
43
44
package swe.HashTable;
import java.util.HashMap;
import java.util.Map;
public class NearestRepeatEntries {
public static int nearestEntry(String[] words){
Map<String,Integer> map = new HashMap<>();
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < words.length ; i++) {
String word = words[i];
if (map.containsKey(word)){
int previousIndex = map.get(word);
int distance = i - previousIndex;
minDistance = Math.min(minDistance,distance);
}
map.put(word,i);
}
return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}
public static void main(String[] args) {
String[] words1 = {
"This",
"is",
"a",
"sentence",
"with",
"is",
"repeated",
"then",
"repeated"
};
System.out.println(nearestEntry(words1)); // Output: 2
String[] words2 = {
"This",
"is",
"a"
};
System.out.println(nearestEntry(words2)); // Output: -1
}
}