题目
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.
答案
class Solution {
public int shortestWordDistance(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);
}
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++) {
if(pos1.get(i).intValue() == pos2.get(j).intValue()) continue;
//System.out.println(Integer.toString(pos1.get(i)) + ' ' + Integer.toString(pos1.get(j)));
ans = Math.min(ans, Math.abs(pos1.get(i) - pos2.get(j)));
}
}
return ans;
}
}