Simple Java solution


  • -1
    I
    public class WordDistance {
    
        private Map<String, List<Integer>> map;
    
        public WordDistance(String[] words) {
            map = new HashMap<>();
            for (int i = 0; i < words.length; ++i) {
                map.computeIfAbsent(words[i], k -> new LinkedList<>()).add(i);
            }
        }
    
        public int shortest(String word1, String word2) {
            List<Integer> list1 = map.get(word1);
            List<Integer> list2 = map.get(word2);
    
            int min = Integer.MAX_VALUE;
    
            for (Integer index1 : list1) {
                for (Integer index2 : list2) {
                    min = Math.min(min, Math.abs(index1 - index2));
                }
            }
    
            return min;
        }
    }

  • 0
    L

    1.wrong lambda express!
    2.linkedList behaved slower.


Log in to reply
 

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