Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the WordDistance class:
WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict. int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.
classWordDistance{ HashMap<String, List<Integer>> map; publicWordDistance(String[] wordsDict){ map = new HashMap<>(); for (int i = 0; i < wordsDict.length; i++){ List<Integer> list = map.getOrDefault(wordsDict[i], new ArrayList<>()); list.add(i); map.put(wordsDict[i], list); } } publicintshortest(String word1, String word2){ List<Integer> l1 = map.get(word1); List<Integer> l2 = map.get(word2); int res = Integer.MAX_VALUE; int i = 0, j = 0; while(i < l1.size() && j < l2.size()){ res = Math.min(res, Math.abs(l1.get(i) - l2.get(j))); if (l1.get(i) < l2.get(j)){ i++; } else{ j++; } } return res; } }
/** * Your WordDistance object will be instantiated and called as such: * WordDistance obj = new WordDistance(wordsDict); * int param_1 = obj.shortest(word1,word2); */