Java Solution using HashMap and TreeSet


  • 0
    A
    HashMap<String, TreeSet<Integer>> map;
        public ShortestWordDistanceII(String[] words) {
            map = new HashMap<>();
            int i = 0;
            for(String word : words)
            {
                if(!map.containsKey(word))
                    map.put(word, new TreeSet<Integer>());
                map.get(word).add(i++);
            }
        }
    
        public int shortest(String word1, String word2) {
            int min = Integer.MAX_VALUE;
            TreeSet<Integer> set1 = map.get(word1);
            TreeSet<Integer> set2 = map.get(word2);
            for(Integer i : set1)
            {
                Integer floor = set2.floor(i);
                min = floor!= null?Math.min(min, Math.abs(i-floor)):min;
                Integer ceiling = set2.ceiling(i);
                min = ceiling!= null?Math.min(min, Math.abs(i-ceiling)):min;
            }
            return min;
        }
    

Log in to reply
 

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