1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class WordDistance {
HashMap<String, List<Integer>> map; HashMap<String,Integer> res;
public WordDistance(String[] wordsDict) { map=new HashMap<>(); res=new HashMap<>(); int n= wordsDict.length; for (int i = 0; i < n; i++) { map.putIfAbsent(wordsDict[i],new ArrayList<>()); map.get(wordsDict[i]).add(i); } }
public int shortest(String word1, String word2) { if(res.containsKey(word1+","+word2)){ return res.get(word1+","+word2); } if(res.containsKey(word2+","+word1)){ return res.get(word2+","+word1); } List<Integer> list1=map.get(word1); List<Integer> list2=map.get(word2); int min=Integer.MAX_VALUE; for (Integer a : list1) { for (Integer b : list2) { min=Math.min(min,Math.abs(a-b)); } } res.put(word1+","+word2,min); return min; } }
|