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: 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.
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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。