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 {
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
String word = words[i];
List<Integer> arr = map.get(word);
if (arr == null) {
arr = new ArrayList<Integer>();
map.put(word, arr);
}
arr.add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> arr1 = map.get(word1);
List<Integer> arr2 = map.get(word2);
int min = Integer.MAX_VALUE;
for (int i : arr1) {
for (int j : arr2) {
min = Math.min(min, Math.abs(i - j));
}
}
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");
==============
public class WordDistance {
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
String word = words[i];
List<Integer> arr = map.get(word);
if (arr == null) {
arr = new ArrayList<Integer>();
map.put(word, arr);
}
arr.add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> arr1 = map.get(word1);
List<Integer> arr2 = map.get(word2);
int min = Integer.MAX_VALUE;
for (int i = 0, j = 0; i < arr1.size() && j < arr2.size();) {
min = Math.min(min, Math.abs(arr1.get(i) - arr2.get(j)));
if (arr1.get(i) > arr2.get(j)) {
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");
没有评论:
发表评论