[leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)

时间:2021-09-11 06:18:45

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. Your method will be called repeatedly many times with different parameters. 

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

 

题意:

还是数组中两个单词的最短距离。

相对于之前[leetcode]243. Shortest Word Distance最短单词距离

这题要求对于function,允许连环call

 

思路:

若对于function,允许连环call,言外之意是,不能naive的扫数组了。

假设 words = ["practice", "makes", "perfect", "coding", "makes", "makes", "coding" ].     word1 = “coding”, word2 = “practice”

用HashMap存储,提高效率。用merge sort思路来同时扫word1的list, word2的list, 更新result

   String           List<Integer>

"practice"              0

 

"makes"               1 -- > 4 -- > 5

                           ^ 指针i 

"perfect"               2

 

"coding"               3 -- > 6 

                           ^ 指针j

 

 

代码:

 1 class WordDistance {
 2     HashMap <String, List<Integer>> map;
 3     
 4     public WordDistance(String[] words) {
 5         map = new HashMap<>();
 6         for(int i = 0 ; i< words.length; i++){
 7             String w = words[i];
 8             if(map.containsKey(w)){
 9                 map.get(w).add(i);
10             }else{
11                 List<Integer> list = new ArrayList<>();
12                 list.add(i);
13                 map.put(w, list);
14             }
15         }
16         
17     }
18 
19     public int shortest(String word1, String word2) {
20         List<Integer> l1 = map.get(word1);
21         List<Integer> l2 = map.get(word2);
22         // --------------merger sort 思想  | ------------------------
23         // --------------merger sort \|/ ------------------------
24         int result = Integer.MAX_VALUE;
25         int i = 0;
26         int j = 0;
27         while(i<l1.size() && j<l2.size()) {
28             result = Math.min(result, Math.abs(l1.get(i)- l2.get(j)));
29             if(l1.get(i)<l2.get(j)){
30                 i++;
31             }else{
32                 j++;
33             }
34         }
35         // --------------merger sort------------------------
36         return result;    
37     }
38 }