n4h0y
BAN USERimport java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class WordFinder {
private Map<String, ArrayList<Integer>> dictionary = new HashMap<String, ArrayList<Integer>>();
public WordFinder(String[] list) {
for (int i = 0; i < list.length; i++) {
addToDictionary(list[i], i);
}
}
private void addToDictionary(String word, int position) {
ArrayList<Integer> positions = dictionary.get(word);
if (positions == null) {
positions = new ArrayList<Integer>();
}
positions.add(position);
dictionary.put(word, positions);
}
public int findDistance(String a, String b) {
if (a == null || b == null) {
return -1;
}
if (a.equals(b)) {
return 0;
}
ArrayList<Integer> posA = dictionary.get(a);
ArrayList<Integer> posB = dictionary.get(b);
if (posA == null || posB == null) {
return -1;
}
int min = 0;
for (int x : posA) {
for (int y : posB) {
int distance = Math.abs(x - y);
if (min > distance || min == 0) {
min = distance;
}
}
}
return min;
}
public static void main(String[] args) {
String[] a = new String[] { "the", "quick", "brown", "fox", "quick" };
WordFinder distanceFinder = new WordFinder(a);
System.out.println("Distance between words is: "
+ distanceFinder.findDistance("fox", "the"));
System.out.println("Distance between words is: "
+ distanceFinder.findDistance("quick", "fox"));
System.out.println("Distance between words is: "
+ distanceFinder.findDistance("brown", "brown"));
System.out.println("Distance between words is: "
+ distanceFinder.findDistance("apple", "mango"));
}
}
Create a Map<String, List<Integer> using the word as the key and the position (index) in the list.
e.g.
"the", "quick", "brown", "fox", "quick"
Quick entry would be "Quick", {1,4}
To calculate the distance just compare the positions of the two words and return the smallest one.
- n4h0y May 28, 2014