原题链接在这里:https://leetcode.com/problems/shortest-word-distance-ii/
类似Shortest Word Distance.
method 会被call好多次,没有必要每次都traverse 一遍words array. 简历一个HashMap, key是word, value是该word出现index的list.
比较word1 和 word2 两个index list. 跟新最小距离.
AC Java:
1 public class WordDistance { 2 HashMap<String,List<Integer>> hm; 3 public WordDistance(String[] words) { 4 hm = new HashMap<String,List<Integer>>(); 5 for(int i = 0; i<words.length; i++){ 6 if(!hm.containsKey(words[i])){ 7 List<Integer> item = new ArrayList<Integer>(); 8 item.add(i); 9 hm.put(words[i],item); 10 }else{ 11 hm.get(words[i]).add(i); 12 } 13 } 14 } 15 16 public int shortest(String word1, String word2) { 17 List<Integer> l1 = hm.get(word1); 18 List<Integer> l2 = hm.get(word2); 19 int res = Integer.MAX_VALUE; 20 for(int i : l1){ 21 for(int j : l2){ 22 res = Math.min(res, Math.abs(j-i)); 23 } 24 } 25 return res; 26 } 27 } 28 29 // Your WordDistance object will be instantiated and called as such: 30 // WordDistance wordDistance = new WordDistance(words); 31 // wordDistance.shortest("word1", "word2"); 32 // wordDistance.shortest("anotherWord1", "anotherWord2");