[LC] 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

class WordDistance {
    private Map<String, List<Integer>> mymap;
    public WordDistance(String[] words) {
        mymap = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            if (mymap.containsKey(words[i])) {
                mymap.get(words[i]).add(i);
            } else {
                List lst = new ArrayList<>();
                lst.add(i);
                mymap.put(words[i], lst);
            }
        }
    }
    
    public int shortest(String word1, String word2) {
        List<Integer> lst1 = mymap.get(word1);
        List<Integer> lst2 = mymap.get(word2);
        int i = 0, j = 0, res = Integer.MAX_VALUE;
        while (i < lst1.size() && j < lst2.size()) {
            res = Math.min(res, Math.abs(lst1.get(i) - lst2.get(j)));
            if (lst1.get(i) < lst2.get(j)) {
                i += 1;
            } else {
                j += 1;
            }
        }
        return res;
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(words);
 * int param_1 = obj.shortest(word1,word2);
 */
posted @ 2020-01-14 11:09  xuan_abc  阅读(113)  评论(0编辑  收藏  举报