Tuesday, December 1, 2015

[leetcode]Shortest Word Distance II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class WordDistance {
    HashMap<String, List<Integer>> lookup = new HashMap<String, List<Integer>>();
    public WordDistance(String[] words) {
        for (int i = 0; i < words.length; i++){
            if (!lookup.containsKey(words[i])){
                lookup.put(words[i], new ArrayList<Integer>());
            }
            lookup.get(words[i]).add(i);
        }
    }

    public int shortest(String word1, String word2) {
        List<Integer> list1 = lookup.get(word1);
        List<Integer> list2 = lookup.get(word2);
        int min = Integer.MAX_VALUE;
        for (int i = 0, j = 0; i < list1.size() && j < list2.size();){
            min = Math.min(min, Math.abs(list1.get(i)-list2.get(j)));
            if (list1.get(i) < list2.get(j)) i++;
            else j++;
        }
        return min;
    }
}

No comments:

Post a Comment