public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int p1 = 1;
int p2 = 1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
if (word1.equals(word2)) {
if (p1 != 1 && i  p1 < min) {
min = i  p1;
}
p1 = i;
} else {
p1 = i;
if (p2 != 1 && p1  p2 < min) {
min = p1  p2;
}
}
} else if (words[i].equals(word2)) {
p2 = i;
if (p1 != 1 && p2  p1 < min) {
min = p2  p1;
}
}
}
return min;
}
}
My Concise JAVA Solution


Nice code that solves the problem in just one function (originally I use a helper function specifically for
word1 == word2
). I rewrite your code in C++.class Solution { public: int shortestWordDistance(vector<string>& words, string word1, string word2) { int n = words.size(), idx1 = 1, idx2 = 1, dist = INT_MAX; for (int i = 0; i < n; i++) { if (words[i] == word1) { if (word1 == word2) { if (idx1 >= 0) dist = min(dist, i  idx1); idx1 = i; } else { idx1 = i; if (idx2 >= 0) dist = min(dist, idx1  idx2); } } else if (words[i] == word2) { idx2 = i; if (idx1 >= 0) dist = min(dist, idx2  idx1); } } return dist; } };

FYI, another readable version:
public int shortestWordDistance(String[] words, String word1, String word2) { int min = Integer.MAX_VALUE; int p1 = 1; int p2 = 1; boolean same = word1.equals(word2); for (int i = 0; i < words.length; i++) { if (words[i].equals(word1)) { if (same) { p2 = p1; // Deal with another pointer too } p1 = i; } else if (words[i].equals(word2)) { p2 = i; } if (p1 != 1 && p2 != 1) { min = Math.min(min, Math.abs(p1  p2)); } } return min; }

@yavinci Is it necessary to do
if (p1 != 1 && p2 != 1) { min = Math.min(min, Math.abs(p1  p2)); }
even if the current word is neither word1 nor word2? Why not just put it in the if and elseif branches?