Java solution- using HashMap<String, List<Integer>>


  • 0
    H
    public class WordDistance {
    
        Map<String, List<Integer>> map;
        
        public WordDistance(String[] words) {
             map = new HashMap<>();
             for (int i = 0; i < words.length; i++) {
                 List<Integer> list;
                 if (map.containsKey(words[i])) {
                     list =  map.get(words[i]);
                     list.add(i);
                 } else {
                     list = new ArrayList<>();
                     list.add(i);
                 }
                  map.put(words[i], list);
             }
        }
    
        public int shortest(String word1, String word2) {
            List<Integer> l1 = map.get(word1);
            List<Integer> l2 = map.get(word2);
            
            int min = Integer.MAX_VALUE;
            for (int p1 : l1) {
                for (int p2 : l2) {
                    min = Math.min(min, Math.abs(p2 - p1));
                }
            }
            return min;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.