Advertisement
md5kafka

Untitled

Nov 4th, 2022
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. class Solution {
  2.     public int shortestDistance(String[] wordsDict, String word1, String word2) {
  3.         Map<String, List<Integer>> map = new HashMap<>();
  4.         for(int i = 0; i < wordsDict.length; i++) {
  5.             List<Integer> indexList = map.getOrDefault(wordsDict[i], new ArrayList<>());
  6.             indexList.add(i);
  7.             map.put(wordsDict[i], indexList);
  8.         }
  9.        
  10.         int min = Integer.MAX_VALUE;
  11.         for(int i : map.get(word1)) {
  12.             for(int j : map.get(word2)) {
  13.                 min = Math.min(Math.abs(i-j), min);
  14.             }
  15.         }
  16.         return min;
  17.     }
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement