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.

class WordDistance {
    private HashMap<String, ArrayList<Integer>> map;

    public WordDistance(String[] words) {
        map = new HashMap<>();
        for(int i = 0; i < words.length; i++) {
            if(!map.containsKey(words[i]))
                map.put(words[i], new ArrayList<>());
            map.get(words[i]).add(i);
        }
    }

    public int shortest(String word1, String word2) {
        ArrayList<Integer> l1 = map.get(word1);
        ArrayList<Integer> l2 = map.get(word2);

        int i = 0;
        int j = 0;
        int res = Integer.MAX_VALUE;

        while(i < l1.size() && j < l2.size()) {
            if(l1.get(i) < l2.get(j)) {
                res = Math.min(res, l2.get(j) - l1.get(i));
                i++;
            } else {
                res = Math.min(res, l1.get(i) - l2.get(j));
                j++;
            }
        }

        return res;
    }
}

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

results matching ""

    No results matching ""