Shortest Word Distance

时间:2023-03-09 16:36:58
Shortest Word Distance

Given a list of words and two words word1 and word2, 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.

分析:

因为word1或者word2在数组里可能有重复,所以,每个词可能会出现在不同的地方。用ArrayList记录word1(word2)出现的index, 然后找到最近的indexs。

考虑到后续问题是如果那个method多被多次call,我们可以用hashmap记录每个word出现的index.

public class WordDistance {
private Map<String, List<Integer>> map;
public WordDistance(String[] words) {
map = new HashMap<String, ArrayList<Integer>>();
for (int i = ; i < words.length; i++) {
if (map.containsKey(words[i])) {
List<Integer> pos = map.get(words[i]);
pos.add(i);
map.put(words[i], pos);
} else {
List<Integer> pos = new ArrayList<>();
pos.add(i);
map.put(words[i], pos);
}
}
} public int shortest(String word1, String word2) {
List<Integer> pos1 = map.get(word1);
List<Integer> pos2 = map.get(word2); int minDistance = Integer.MAX_VALUE;
int i = ;
int j = ;
while (i < pos1.size() && j < pos2.size()) {
int p1 = pos1.get(i);
int p2 = pos2.get(j);
if (p1 < p2) {
minDistance = Math.min(minDistance, p2 - p1);
i++;
} else {
minDistance = Math.min(minDistance, p1 - p2);
j++;
}
} return minDistance;
}
}

如果两个单词不一样,而且只被call一次,那么下面这个方法也不错。

 public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int index1 = -;
int index2 = -;
int min = Integer.MAX_VALUE;
for(int i = ; i < words.length; i++){
if(words[i].equals(word1)){
index1 = i;
}else if(words[i].equals(word2)){
index2 = i;
}
if(index1 != - && index2 != -){
min = Math.min(min, Math.abs(index1 - index2));
}
}
return min;
}
}