Created
April 19, 2016 02:14
-
-
Save cangoal/a2724d173c2a1ee81644b140481f41c7 to your computer and use it in GitHub Desktop.
LeetCode - Shortest Word Distance II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 called repeatedly 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. | |
public class WordDistance { | |
private Map<String, List<Integer>> map; | |
public WordDistance(String[] words) { | |
if(words.length != 0){ | |
map = new HashMap<String, List<Integer>>(); | |
for(int i = 0; i < words.length; i++){ | |
if(!map.containsKey(words[i])){ | |
map.put(words[i], new ArrayList<Integer>()); | |
} | |
map.get(words[i]).add(i); | |
} | |
} | |
} | |
public int shortest(String word1, String word2) { | |
if(word1 == null || word2 == null || !map.containsKey(word1) || !map.containsKey(word2)) return -1; | |
int min = Integer.MAX_VALUE, i = 0, j = 0; | |
List<Integer> lst1 = map.get(word1); | |
List<Integer> lst2 = map.get(word2); | |
int len1 = lst1.size(), len2 = lst2.size(); | |
while(i < len1 && j < len2){ | |
int index1 = lst1.get(i), index2 = lst2.get(j); | |
min = Math.min(min, Math.abs(index1 - index2)); | |
if(index1 > index2) j++; | |
else i++; | |
} | |
return min; | |
} | |
} | |
// Your WordDistance object will be instantiated and called as such: | |
// WordDistance wordDistance = new WordDistance(words); | |
// wordDistance.shortest("word1", "word2"); | |
// wordDistance.shortest("anotherWord1", "anotherWord2"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment