Skip to content

Instantly share code, notes, and snippets.

@amilcar-andrade
Created May 9, 2017 03:37
Show Gist options
  • Save amilcar-andrade/aa48d9f01c99fd742594629bf0f2b1b0 to your computer and use it in GitHub Desktop.
Save amilcar-andrade/aa48d9f01c99fd742594629bf0f2b1b0 to your computer and use it in GitHub Desktop.
WordDistanceFinder solution
/* 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);
*
* "quick" appears twice in the input. There are two possible distance values for "quick" and "fox":
* (3 - 1) = 2 and (4 - 3) = 1.
* Since we have to return the shortest distance between the two words we return 1.
*/
class WordDistanceFinder {
final List<String> words;
public WordDistanceFinder (List<String> words) {
this.words = words;
}
public int distance (String wordOne, String wordTwo) {
if (wordTwo == null || wordOne == null) {
throw new NullPointerException("Words cannot be null");
}
if (wordOne.equals(wordTwo)) {
return 0;
}
Integer lastWordOneIndex = null;
Integer lastWordTwoIndex = null;
Integer minValue = Integer.MAX_VALUE;
for (int i = 0; i < words.size(); i++) {
final String currentWord = words.get(i);
if (wordOne.equals(currentWord)) {
lastWordOneIndex = i;
if (lastWordTwoIndex != null) {
minValue = Math.min(minValue, lastWordOneIndex - lastWordTwoIndex);
}
} else if (wordTwo.equals(currentWord)) {
lastWordTwoIndex = i;
if (lastWordOneIndex != null) {
minValue = Math.min(minValue, lastWordTwoIndex - lastWordOneIndex);
}
}
}
if (lastWordTwoIndex == null || lastWordOneIndex == null) {
throw new InvalidParameterException("Words are not on the list");
}
return minValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment