题目
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
答案
class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
// Get all possible positions for these two words
List<Integer> pos1 = new ArrayList<>();
List<Integer> pos2 = new ArrayList<>();
int ans = Integer.MAX_VALUE;
for(int i = 0; i < words.length; i++) {
if(words[i].equals(word1)) {
pos1.add(i);
}
else if(words[i].equals(word2)) {
pos2.add(i);
}
}
// For each pair of position (i, j), record min(abs(i - j))
for(int i = 0; i < pos1.size(); i++) {
for(int j = 0; j < pos2.size(); j++) {
ans = Math.min(ans, Math.abs(pos1.get(i) - pos2.get(j)));
}
}
return ans;
}
}