Example:
WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
assert(finder.distance("fox","the") == 3);
assert(finder.distance("quick", "fox") == 1);
I have the following solution, which appears to be O(n), but I'm not sure if there is a better solution out there. Does anyone have any idea?
String targetString = "fox";
String targetString2 = "the";
double minDistance = Double.POSITIVE_INFINITY;
for(int x = 0; x < strings.length; x++){
if(strings[x].equals(targetString)){
for(int y = x; y < strings.length; y++){
if(strings[y].equals(targetString2))
if(minDistance > (y - x))
minDistance = y - x;
}
for(int y = x; y >=0; y--){
if(strings[y].equals(targetString2))
if(minDistance > (x - y))
minDistance = x - y;
}
}
}
for
loops. And yes, this can be done in O(n), but I'm pretty sure this is homework, so that's all I'll say for now. – Santossantosdumont