[LeetCode] 244. Shortest Word Distance II

47次阅读

共计 1076 个字符,预计需要花费 3 分钟才能阅读完成。

Problem
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: 3Input: word1 = “makes”, word2 = “coding”Output: 1Note:You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Solution
class WordDistance {
private Map<String, List<Integer>> map;
public WordDistance(String[] words) {
map = new HashMap<String, List<Integer>>();
for(int i = 0; i < words.length; i++) {
String word = words[i];
if (!map.containsKey(word)) map.put(word, new ArrayList<>());
map.get(word).add(i);
}
}

public int shortest(String word1, String word2) {
List<Integer> list1 = map.get(word1);
List<Integer> list2 = map.get(word2);
int min = Integer.MAX_VALUE;
int i = 0, j = 0;
while (i < list1.size() && j < list2.size()) {
int index1 = list1.get(i), index2 = list2.get(j);
if (index1 < index2) {
min = Math.min(min, index2 – index1);
i++;
} else {
min = Math.min(min, index1 – index2);
j++;
}
}
return min;
}
}

正文完
 0