/* This class will be given a list of words (such as might be tokenized
* from a paragraph of text), and will provide a method that takes two
* words and returns the shortest distance (in words) between those two
* words in the provided text.
* Example:
* WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
* assert(finder.distance("fox","the") == 3);
* assert(finder.distance("quick", "fox") == 1);
* /
public int findShortestDist(String[] words, String wordA, String wordB) { int n = words.length; int dist = n; int posA = -1, posB = -1; for(int i=0; i<n; i++) { if(words[i].equals(wordA)) { posA = i; if(posB != -1) { dist = Math.min(dist, posA-posB); } } else if(words[i].equals(wordB)) { posB = i; if(posA != -1) { dist = Math.min(dist, posB-posA); } } } return (posA == -1 || posB == -1) ? -1 : dist; }
另外一种简单的写法:
public int findShortestDist(String[] words, String wordA, String wordB) { int n = words.length; int dist = n+1; int posA = -1, posB = -1; for(int i=0; i<n; i++) { if(words[i].equals(wordA)) { posA = i; } else if(words[i].equals(wordB)) { posB = i; } if(posA != -1 && posB != -1) { dist = Math.min(dist, Math.abs(posA-posB)); } } return dist > n ? -1 : dist; }
Reference:
http://www.careercup.com/question?id=5725709041401856
http://www.geeksforgeeks.org/find-the-minimum-distance-between-two-numbers/