Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 25, 2019 18:56
Show Gist options
  • Save shixiaoyu/b3caecd291de207542d3c850dd588991 to your computer and use it in GitHub Desktop.
Save shixiaoyu/b3caecd291de207542d3c850dd588991 to your computer and use it in GitHub Desktop.
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0 || word1 == null || word2 == null || word1.equals(word2)) {
return -1;
}
int minDistance = words.length;
int wordIndex1 = -1;
int wordIndex2 = -1;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
wordIndex1 = i;
if (wordIndex2 != -1) {
minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
}
}
if (words[i].equals(word2)) {
wordIndex2 = i;
if (wordIndex1 != -1) {
minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
}
}
}
return minDistance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment