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 = 0; 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 = 0; int j = 0; 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一次,那么下面这个方法也不错。
1 public class Solution { 2 public int shortestDistance(String[] words, String word1, String word2) { 3 int index1 = -1; 4 int index2 = -1; 5 int min = Integer.MAX_VALUE; 6 for(int i = 0; i < words.length; i++){ 7 if(words[i].equals(word1)){ 8 index1 = i; 9 }else if(words[i].equals(word2)){ 10 index2 = i; 11 } 12 if(index1 != -1 && index2 != -1){ 13 min = Math.min(min, Math.abs(index1 - index2)); 14 } 15 } 16 return min; 17 } 18 }

浙公网安备 33010602011771号