乐趣区

[LeetCode] 245. Shortest Word Distance III

Problem
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the list.
Example:Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Input: word1 =“makes”, word2 =“coding”Output: 1Input: word1 = “makes”, word2 = “makes”Output: 3Note:You may assume word1 and word2 are both in the list.
Solution
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
for(int i = 0; i < words.length; i++) {
String word = words[i];
if (!map.containsKey(word)) map.put(word, new ArrayList<>());
map.get(word).add(i);
}
if (word1.equals(word2)) {
List<Integer> list = map.get(word1);
if (list.size() < 2) return -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < list.size()-1; i++) {
min = Math.min(min, list.get(i+1)-list.get(i));
}
return min;
}
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()) {
int index1 = list1.get(i), index2 = list2.get(j);
if (index1 < index2) {
min = Math.min(min, index2 – index1);
i++;
} else {
min = Math.min(min, index1 – index2);
j++;
}
}
return min;
}
}

退出移动版