Share my JAVA solution with HashMap and two list.


  • 0

    Use HashMap to record the index list.

    HashMap<String, List<Integer>> map;
        public WordDistance(String[] words) {
            map = new HashMap<>();
            for(int i = 0; i < words.length; i++){
                String s = words[i];
                if(!map.containsKey(s))
                    map.put(s, new LinkedList<>());
                map.get(s).add(i);
            }
        }
        
        public int shortest(String word1, String word2) {
            List<Integer> list1 = map.get(word1);
            List<Integer> list2 = map.get(word2);
            int dp = Integer.MAX_VALUE;
            for(int i = 0, j = 0; i < list1.size() && j < list2.size(); ){
                dp = Math.min(dp, Math.abs(list1.get(i) - list2.get(j)));
                if(list1.get(i) < list2.get(j)) i++;
                else j++;
            }
            return dp;
        }
    
    

Log in to reply
 

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