Java HashMap Solution


  • 0
    A
    public class WordDistance {
    
        Map<String, List<Integer>> map = new HashMap();
        
        public WordDistance(String[] words) {
            //build Map
            for(int i=0;i<words.length;i++) {
                List<Integer> list;
                if(!map.containsKey(words[i])) {
                    list = new ArrayList<Integer>();
                } else {
                    list = map.get(words[i]);
                }
                list.add(i);
                map.put(words[i], list);
            }
        }
        
        public int shortest(String word1, String word2) {
            int result = Integer.MAX_VALUE;
            int i=0;
            int j=0;
            List<Integer> list1 = map.get(word1);
            List<Integer> list2 = map.get(word2);
            
            while(i < list1.size() && j < list2.size()) {
                if(list1.get(i) < list2.get(j)){
                    result = Math.min(result, list2.get(j) - list1.get(i));
                    i++;
                } else {
                    result = Math.min(result, list1.get(i) - list2.get(j));
                    j++;
                }
            }
            return result;
        }
    }

Log in to reply
 

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