I'm trying to write a program that quickly finds all words that match a string with wildcards and known letters. For example, L*G would return LOG, LAG, LEG. I'm looking for something that would give me very fast lookup, but I don't care about time it takes to create the tree in the first place.
My idea is a Hashmap of "Triples" mapping to an ArrayList of Strings: basically, a list of all Strings that match the criteria for a certain index, character at that index, and length.
But my issue now is generating a good hash function for these "Triples" such that every triplet is unique.
Here's my code for what I have right now.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CWSolutionT {
HashMap<Triple, ArrayList<String>> tripleMap = new HashMap<Triple, ArrayList<String>>();
public CWSolutionT(List<String> allWords) {
for (String word : allWords) {
for (int letter = 0; letter < word.length(); letter++) {
ArrayList<String> tempList = new ArrayList<String>();
Triple key = new Triple(letter, word.charAt(letter),
word.length());
if (tripleMap.get(key) == null) {
tempList.add(word);
tripleMap.put(key, tempList);
} else {
tempList = tripleMap.get(key);
tempList.add(word);
tripleMap.put(key, tempList);
}
}
}
}
public List<String> solutions(String pattern, int maxRequired) {
List<String> sol = new ArrayList<String>();
List<List<String>> solList = new ArrayList<List<String>>();
int length = pattern.length();
for (int i = 0; i < length; i++) {
if (pattern.charAt(i) != '*') {
Triple key = new Triple(i, pattern.charAt(i), pattern.length());
solList.add(tripleMap.get(key));
}
}
if (solList.size() == 0) {
// implement later
}
if (solList.size() == 1)
return solList.get(0);
for (List<String> list : solList) {
sol.retainAll(list);
}
return sol;
}
private class Triple {
public final int index;
public final char letter;
public final int length;
public Triple(int ind, char let, int len) {
index = ind;
letter = let;
length = len;
}
public boolean equals(Object o) {
if (o == null)
return false;
if (o == this)
return true;
if (!(o instanceof Triple)) {
return false;
}
Triple comp = (Triple) o;
if (this.hashCode() == comp.hashCode())
return true;
return false;
}
public String toString() {
return "(" + index + ", " + letter + ", " + length + ")";
}
public int hashCode() {
return (int) (.5 * (index + letter + length)
* (index + letter + length + 1) + letter + length);
}
}
}