This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be calledrepeatedly many times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and 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.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
这道题的I III其实还是比较简单的,II相对麻烦一点,一开始写的时候基本都是超时了,比较好的思路是通过一个hashmap存储每个单词出现的索引,然后每次调用时取出两个索引list进行比较求最小距离:
public class WordDistance { private String[] words; private Map<String,List<Integer>> map=new HashMap<>(); public WordDistance(String[] words) { this.words=words; for(int i=0;i<words.length;i++){ if(map.get(words[i])==null){ List<Integer> list=new ArrayList<>(); list.add(i); map.put(words[i],list); } else map.get(words[i]).add(i); } } public int shortest(String word1, String word2) { List<Integer> list1=map.get(word1); List<Integer> list2=map.get(word2); int min=Integer.MAX_VALUE; int i=0,j=0; while(i<list1.size()&&j<list2.size()){ min=Math.min(min,Math.abs(list1.get(i)-list2.get(j))); if(list1.get(i)<list2.get(j)) i++; else j++; } return min; } }