Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class WordDistance {
- Map<String, List<Integer>> map = new HashMap<>();
- public WordDistance(String[] wordsDict) {
- for(int i = 0; i < wordsDict.length; i++) {
- List<Integer> indexList = map.getOrDefault(wordsDict[i], new ArrayList<>());
- indexList.add(i);
- map.put(wordsDict[i], indexList);
- }
- }
- public int shortest(String word1, String word2) {
- int min = Integer.MAX_VALUE;
- for(int i : map.get(word1)) {
- for(int j : map.get(word2)) {
- min = Math.min(Math.abs(i-j), min);
- }
- }
- return min;
- }
- }
- /**
- * Your WordDistance object will be instantiated and called as such:
- * WordDistance obj = new WordDistance(wordsDict);
- * int param_1 = obj.shortest(word1,word2);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement