Advertisement
md5kafka

Untitled

Nov 4th, 2022
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. class WordDistance {
  2.     Map<String, List<Integer>> map = new HashMap<>();
  3.    
  4.     public WordDistance(String[] wordsDict) {
  5.        
  6.         for(int i = 0; i < wordsDict.length; i++) {
  7.             List<Integer> indexList = map.getOrDefault(wordsDict[i], new ArrayList<>());
  8.             indexList.add(i);
  9.             map.put(wordsDict[i], indexList);
  10.         }
  11.     }
  12.    
  13.     public int shortest(String word1, String word2) {
  14.         int min = Integer.MAX_VALUE;
  15.         for(int i : map.get(word1)) {
  16.             for(int j : map.get(word2)) {
  17.                 min = Math.min(Math.abs(i-j), min);
  18.             }
  19.         }
  20.         return min;
  21.     }
  22. }
  23.  
  24. /**
  25.  * Your WordDistance object will be instantiated and called as such:
  26.  * WordDistance obj = new WordDistance(wordsDict);
  27.  * int param_1 = obj.shortest(word1,word2);
  28.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement