This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
[分析]
在构造函数将各单词出现的所有位置保存在HashMap中,调用shortest()方法时,从HashMap中获取两单词的位置列表,两个列表是已排序的,因此可使用类似MergeSort的思路求解最短距离。
[ref]
[url]https://leetcode.com/discuss/50190/java-solution-using-hashmap[/url]
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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
[分析]
在构造函数将各单词出现的所有位置保存在HashMap中,调用shortest()方法时,从HashMap中获取两单词的位置列表,两个列表是已排序的,因此可使用类似MergeSort的思路求解最短距离。
[ref]
[url]https://leetcode.com/discuss/50190/java-solution-using-hashmap[/url]
public class WordDistance {
private HashMap<String, List<Integer>> indexer = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
if (words == null) return;
for (int i = 0; i < words.length; i++) {
if (indexer.containsKey(words[i])) {
indexer.get(words[i]).add(i);
} else {
List<Integer> positions = new ArrayList<Integer>();
positions.add(i);
indexer.put(words[i], positions);
}
}
}
public int shortest(String word1, String word2) {
List<Integer> posList1 = indexer.get(word1);
List<Integer> posList2 = indexer.get(word2);
int i = 0, j = 0;
int diff = Integer.MAX_VALUE;
while (i < posList1.size() && j < posList2.size()) {
int pos1 = posList1.get(i), pos2 = posList2.get(j);
if (pos1 < pos2) {
diff = Math.min(diff, pos2 - pos1);
i++;
} else {
diff = Math.min(diff, pos1 - pos2);
j++;
}
}
return diff;
}
}
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");

本文介绍如何优化WordDistance类,使其能够高效地在给定单词列表中查找任意两个单词之间的最短距离。通过利用HashMap存储单词位置并采用排序列表进行比较,实现快速查找功能。
79

被折叠的 条评论
为什么被折叠?



