Last active
April 19, 2016 02:23
-
-
Save cangoal/cc519c1e843777f319e5a63db930cfd0 to your computer and use it in GitHub Desktop.
LeetCode - Shortest Word Distance
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
// Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. | |
// For example, | |
// Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. | |
// Given word1 = “coding”, word2 = “practice”, return 3. | |
// Given word1 = "makes", word2 = "coding", return 1. | |
// Note: | |
// You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. | |
public int shortestDistance(String[] words, String word1, String word2) { | |
if(words == null || words.length < 2) return -1; | |
int min = Integer.MAX_VALUE, i = -1, j = -1; | |
for(int k = 0; k < words.length; k++){ | |
if(words[k].equals(word1)) i = k; | |
if(words[k].equals(word2)) j = k; | |
if(i != -1 && j != -1){ | |
min = Math.min(Math.abs(i - j), min); | |
} | |
} | |
return min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment