public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0 || word1 == null || word2 == null) {
return 0;
}
int min = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1) || words[i].equals(word2)) {
if (index != -1 && !words[index].equals(words[i])) {
min = Math.min(min, i - index);
}
index = i;
}
}
return min;
}
}
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0 || word1 == null || word2 == null) {
return 0;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
min = Math.min(expand(word2, i, words), min);
}
}
return min;
}
public int expand(String word2, int i, String[] words) {
for (int j = 1; j < words.length; j++) {
int index1 = i + j;
int index2 = i - j;
if (index1 < words.length) {
if (word2.equals(words[index1])) {
return j;
}
}
if (index2 >= 0) {
if (word2.equals(words[index2])) {
return j;
}
}
}
return 0;
}
}
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length < 1) return -1;
int len = words.length;
Map<String, List<Integer>> map = new HashMap<>();
for (int i = 0; i < len; i++) {
map.putIfAbsent(words[i], new ArrayList<Integer>());
map.get(words[i]).add(i);
}
int distance = Integer.MAX_VALUE;
for (int i : map.get(word1)) {
for (int j : map.get(word2)) {
distance = Math.min(distance, Math.abs(i - j));
}
}
return distance;
}
}