Sunday, January 31, 2021

244. Shortest Word Distance II

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. 

My answer: same as leetcode answer. Since indices1 and indices2 are already sorted, we just need to move i/j around so that indices1[i] and indices2[j] is always next to each. Once either one reaches end of list meaning 2 things: 1) if value of the other one is greater, we have already checked nearest ones in the other one, given the end value; 2) if value of the other one is smaller, we need to move the other indices until it is bigger than the end value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class WordDistance {

    Map<String, List<Integer>> wordIndices = new HashMap<String, List<Integer>>();
    public WordDistance(String[] words) {
        for (int i = 0; i < words.length; i ++) {
            List<Integer> indices = wordIndices.getOrDefault(words[i], new ArrayList<Integer>());
            indices.add(i);
            wordIndices.put(words[i], indices);
        }
    }
    
    public int shortest(String word1, String word2) {
        List<Integer> indices1 = wordIndices.getOrDefault(word1, new ArrayList<Integer>());
        List<Integer> indices2 = wordIndices.getOrDefault(word2, new ArrayList<Integer>());

        int i = 0;
        int j = 0;
        int minDistance = Integer.MAX_VALUE;
        while (i < indices1.size() && j < indices2.size()) {
            minDistance = Math.min(minDistance, Math.abs(indices1.get(i) - indices2.get(j)));
            if (indices1.get(i) > indices2.get(j)) {
                j ++;
            } else {
                i ++;
            }
        }
        return minDistance;
    }
}

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


No comments:

Post a Comment