Created
December 25, 2019 18:56
-
-
Save shixiaoyu/b3caecd291de207542d3c850dd588991 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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