Easy to understand accepted java solution


  • 0
    R
    class WordDistance {
        
        private Map<String, List<Integer>> map;
        
        public WordDistance(String[] words) {
            map = new HashMap<String, List<Integer>>();
            for (int i = 0;i < words.length;i++) {
                String s = words[i];
                List<Integer> list = map.getOrDefault(s, new ArrayList<Integer>());
                list.add(i);
                map.put(s, list);
            }
        }
        
        public int shortest(String word1, String word2) {
            List<Integer> list1 = map.get(word1);
            List<Integer> list2 = map.get(word2);
            Collections.sort(list1);
            Collections.sort(list2);
            int i = 0;
            int j = 0;
            int min = Integer.MAX_VALUE;
            while (i < list1.size() && j < list2.size()) {
                if (list1.get(i) <= list2.get(j)) {
                    min = Math.min(min, list2.get(j) - list1.get(i));
                    i++;
                } else {
                    min = Math.min(min, list1.get(i) - list2.get(j));
                    j++;
                }
            }
            return min;
        } 
        
    }
    
    /**
     * Your WordDistance object will be instantiated and called as such:
     * WordDistance obj = new WordDistance(words);
     * int param_1 = obj.shortest(word1,word2);
     */
    

Log in to reply
 

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