Advertisement
1988coder

244. Shortest Word Distance II

Jan 15th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/shortest-word-distance-ii/
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6.  
  7. /**
  8.  * Create a map of each word and its index in words array. Now compare this
  9.  * index lists of 2 words to find the minimum distance.
  10.  *
  11.  * Time Complexity: WordDistance Constructor = O(L * N). shortest function = O(I
  12.  * + J) = O(N). I = Length of indexList1. J = Length of indexList2. In worst
  13.  * case sum of I & J will be N.
  14.  *
  15.  * Space Complexity: O(L * N). Size of the map.
  16.  *
  17.  * L = Average length of a word in words array. N = Number words in the input
  18.  * array.
  19.  */
  20. class WordDistance {
  21.  
  22.     HashMap<String, List<Integer>> map;
  23.  
  24.     public WordDistance(String[] words) {
  25.         map = new HashMap<>();
  26.         if (words == null || words.length == 0) {
  27.             return;
  28.         }
  29.  
  30.         for (int i = 0; i < words.length; i++) {
  31.             if (!map.containsKey(words[i])) {
  32.                 map.put(words[i], new ArrayList<Integer>());
  33.             }
  34.             map.get(words[i]).add(i);
  35.         }
  36.     }
  37.  
  38.     public int shortest(String word1, String word2) {
  39.         if (word1 == null || word2 == null || !map.containsKey(word1) || !map.containsKey(word2)) {
  40.             return -1;
  41.         }
  42.         if (word1.equals(word2)) {
  43.             return 0;
  44.         }
  45.  
  46.         List<Integer> list1 = map.get(word1);
  47.         List<Integer> list2 = map.get(word2);
  48.  
  49.         int result = Integer.MAX_VALUE;
  50.         int i = 0;
  51.         int j = 0;
  52.         while (i < list1.size() && j < list2.size()) {
  53.             int index1 = list1.get(i);
  54.             int index2 = list2.get(j);
  55.             if (index1 < index2) {
  56.                 result = Math.min(result, index2 - index1);
  57.                 i++;
  58.             } else {
  59.                 result = Math.min(result, index1 - index2);
  60.                 j++;
  61.             }
  62.         }
  63.  
  64.         return result;
  65.     }
  66. }
  67.  
  68. /**
  69.  * Your WordDistance object will be instantiated and called as such:
  70.  *
  71.  * WordDistance obj = new WordDistance(words);
  72.  *
  73.  * int param_1 = obj.shortest(word1,word2);
  74.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement