File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class WordDistance {
2
+ HashMap <String , ArrayList <Integer >> map ;
3
+
4
+ public WordDistance (String [] words ) {
5
+ map = new HashMap <>();
6
+
7
+ for (int i = 0 ; i < words .length ; i ++) {
8
+ ArrayList <Integer > a ;
9
+ if (map .containsKey (words [i ])) {
10
+ a = map .get (words [i ]);
11
+ } else {
12
+ a = new ArrayList <>();
13
+ }
14
+ a .add (i );
15
+ map .put (words [i ], a );
16
+ }
17
+ }
18
+
19
+ // Important to optimize this for O(n) instead of O(n^2) where n is the avg list length
20
+ public int shortest (String word1 , String word2 ) {
21
+ ArrayList <Integer > w1 = map .get (word1 );
22
+ ArrayList <Integer > w2 = map .get (word2 );
23
+
24
+ int dist = Integer .MAX_VALUE ;
25
+
26
+ for (int i = 0 , j = 0 ; i < w1 .size () && j < w2 .size (); ) {
27
+ int index1 = w1 .get (i );
28
+ int index2 = w2 .get (j );
29
+
30
+ if (index1 < index2 ) {
31
+ dist = Math .min (dist , index2 - index1 );
32
+ i ++;
33
+ } else {
34
+ dist = Math .min (dist , index1 - index2 );
35
+ j ++;
36
+ }
37
+ }
38
+
39
+ return dist ;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Your WordDistance object will be instantiated and called as such:
45
+ * WordDistance obj = new WordDistance(words);
46
+ * int param_1 = obj.shortest(word1,word2);
47
+ */
You can’t perform that action at this time.
0 commit comments