Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 19, 2016 02:39
Show Gist options
  • Save cangoal/01ab6c181e7f7dc106848becd7d702cd to your computer and use it in GitHub Desktop.
Save cangoal/01ab6c181e7f7dc106848becd7d702cd to your computer and use it in GitHub Desktop.
LeetCode - Shortest Word Distance III
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
// 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.
// For example,
// Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
// Given word1 = “makes”, word2 = “coding”, return 1.
// Given word1 = "makes", word2 = "makes", return 3.
// Note:
// You may assume word1 and word2 are both in the list.
public int shortestWordDistance(String[] words, String word1, String word2) {
if(words == null || words.length < 2) return -1;
int min = Integer.MAX_VALUE, i = -1, j = -1, pre = -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){
if(i != j) min = Math.min(Math.abs(i - j), min);
else{
if(pre != -1) min = Math.min(Math.abs(i - pre), min);
pre = i; i = -1; j = -1;
}
}
}
return min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment