245. Shortest Word Distance III
Shortest Word Distance III
Solution
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
Map<String, List<Integer>> map = new HashMap<>();
for(int i = 0; i < words.length; i ++) {
if (map.containsKey(words[i])) {
map.get(words[i]).add(i);
} else {
List<Integer> indices = new ArrayList<>();
indices.add(i);
map.put(words[i], indices);
}
}
List<Integer> indices1 = map.get(word1);
List<Integer> indices2 = map.get(word2);
int distance = Integer.MAX_VALUE;
for(int i : indices1) {
for(int j : indices2) {
if(i!=j){
distance = Math.min(distance, Math.abs(i-j));}
}
}
return distance;
}
}Last updated