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:
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.
题意:给定数组,和两个word,word,要求构造一个类,计算两者的最短距离,因为我们要给出很多组不同的两个word,你会怎么组织这个类呢?
分类:数组
解法1:在构造函数,使用hashMap来记录每个单词的位置
在计算最短距离的函数中,两个列表是已排序的,因此可使用类似MergeSort的思路求解最短距离。
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;
}
}
最短单词距离算法设计

本文介绍了一种高效算法,用于解决给定单词列表中任意两单词间的最短距离问题。通过构造类并利用哈希映射存储单词位置,实现快速查询。适用于需多次查询不同单词组合场景。
513

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



