Leetcode 0244: Shortest Word Distance II

Title description:

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.

Example :

Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].

Input: word1 = “coding”, word2 = “practice”
Output: 3

Input: word1 = “makes”, word2 = “coding”
Output: 1

Note:

You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Time complexity: Constructor O(n), Find difference function O(max(K,L)) = O(n). K, L is the number of occurrences of two words
Space complexity: O(n)

class WordDistance {
    
    
    Map<String, List<Integer>> map;
    public WordDistance(String[] words) {
    
    
        this.map = new HashMap<String, List<Integer>>();
         for(int i = 0; i < words.length; i++){
    
    
             String str = words[i];
             List<Integer> list = this.map.getOrDefault(str, new ArrayList<Integer>());
             list.add(i);
             this.map.put(str, list);
         }
    }
    
    public int shortest(String word1, String word2) {
    
    
        List<Integer> list1 = this.map.get(word1);
        List<Integer> list2 = this.map.get(word2);
        int minDiff = Integer.MAX_VALUE;
        int l1 = 0;
        int l2 = 0;
        while(l1 < list1.size() && l2 < list2.size()){
    
    
            int index1 = list1.get(l1);
            int index2 = list2.get(l2);
            minDiff = Math.min(minDiff, Math.abs(index1 - index2));
            if(index1 < index2){
    
    
                l1++;
            }else{
    
    
                l2++;
            }
        }
        return minDiff;
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(words);
 * int param_1 = obj.shortest(word1,word2);
 */

Guess you like

Origin blog.csdn.net/weixin_43946031/article/details/113939988