LeetCode刷题实战244:最短单词距离 II
共 3825字,需浏览 8分钟
·
2021-04-25 14:04
示例
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
解题
public class WordDistance {
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
// 统计每个单词出现的下标存入哈希表中
for(int i = 0; i < words.length; i++){
List<Integer> cnt = map.get(words[i]);
if(cnt == null){
cnt = new ArrayList<Integer>();
}
cnt.add(i);
map.put(words[i], cnt);
}
}
public int shortest(String word1, String word2) {
List<Integer> idx1 = map.get(word1);
List<Integer> idx2 = map.get(word2);
int distance = Integer.MAX_VALUE;
int i = 0, j = 0;
// 每次比较两个下标列表最小的下标,然后把跳过较小的那个
while(i < idx1.size() && j < idx2.size()){
distance = Math.min(Math.abs(idx1.get(i) - idx2.get(j)), distance);
if(idx1.get(i) < idx2.get(j)){
i++;
} else {
j++;
}
}
return distance;
}
}