Shortest Word Distance II
Input: word1 = “coding”, word2 = “practice”
Output: 3Input: word1 = "makes", word2 = "coding"
Output: 1class WordDistance {
public String[] words = null;
public HashMap<String,List<Integer>> map = new HashMap<>();
public WordDistance(String[] words) {
for(int i = 0; i < words.length;i++){
if(map.containsKey(words[i])){
map.get(words[i]).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(words[i],list);
}
}
}
public int shortest(String word1, String word2) {
if(word1 == null || word2 == null || !map.containsKey(word1) || !map.containsKey(word2)){
return -1;
}
List<Integer> list1 = map.get(word1);
List<Integer> list2 = map.get(word2);
int res = Integer.MAX_VALUE;
//for(int i : list1){
// for(int j : list2){
// res = Math.min(res,Math.abs(i - j));
// }
//}
int i =0, j = 0;
while(i < list1.size() && j < list2.size()){
int a = list1.get(i);
int b = list2.get(j);
res = Math.min(res,Math.abs(a - b));
//找最小距离,所以尽可能缩小a和b的差距
if(a < b)
i++;
if(a > b)
j++;
}
return res;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/Last updated