这个想法是使用前缀树来构建一个字典,将列表中的单词映射到其最大的唯一超级字符串。一旦我们构建了这个,对于超字符串与单词本身相同的单词,我们尝试对列表中最接近的单词进行模糊匹配并返回其超字符串。所以“dsk”会发现“des”或“desk”是最接近的,我们提取它的超字符串。
import org.apache.commons.collections4.Trie;
import org.apache.commons.collections4.trie.PatriciaTrie;
import java.util.*;
import java.util.SortedMap;
public class Test {
static Trie trie = new PatriciaTrie<>();
public static int cost(char a, char b) {
return a == b ? 0 : 1;
}
public static int min(int... numbers) {
return Arrays.stream(numbers).min().orElse(Integer.MAX_VALUE);
}
// this function taken from https://www.baeldung.com/java-levenshtein-distance
static int editDistance(String x, String y) {
int[][] dp = new int[x.length() + 1][y.length() + 1];
for (int i = 0; i <= x.length(); i++) {
for (int j = 0; j <= y.length(); j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else {
dp[i][j] = min(dp[i - 1][j - 1] + cost(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1,
dp[i][j - 1] + 1);
}
}
}
return dp[x.length()][y.length()];
}
/*
* custom dictionary that map word to its biggest super string.
* mob -> mobile, mobi -> mobile, desk -> desktop
*/
static void initMyDictionary(List<String> myList) {
for (String word : myList) {
trie.put(word.toLowerCase(), "0"); // putting 0 as default
}
for (String word : myList) {
SortedMap<String, String> prefixMap = trie.prefixMap(word);
String bigSuperString = "";
for (Map.Entry<String, String> m : prefixMap.entrySet()) {
int max = 0;
if (m.getKey().length() > max) {
max = m.getKey().length();
bigSuperString = m.getKey();
}
// System.out.println(bigString + " big");
}
for (Map.Entry<String, String> m : prefixMap.entrySet()) {
m.setValue(bigSuperString);
// System.out.println(m.getKey() + " - " + m.getValue());
}
}
}
/*
* find closest words for a given String.
*/
static List<String> findClosest(String q, List<String> myList) {
List<String> res = new ArrayList();
for (String w : myList) {
if (editDistance(q, w) == 1) // just one char apart edit distance
res.add(w);
}
return res;
}
public static void main(String[] args) {
List<String> myList = new ArrayList<>(
Arrays.asList("mob", "MOB", "mobi", "mobil", "mobile", "desk", "desktop", "dsk"));
initMyDictionary(myList); // build my custom dictionary using prefix tree
// String query = "mob"
// String query = "mobile";
// String query = "des";
String query = "dsk";
// if the word and its superstring are the same, then we try to find the closest
// words from list and lookup the superstring in the dictionary.
if (query.equals(trie.get(query.toLowerCase()))) {
for (String w : findClosest(query, myList)) { // try to resolve the ambiguity here if there are multiple closest words
System.out.println(query + " -fuzzy maps to-> " + trie.get(w));
}
} else {
System.out.println(query + " -maps to-> " + trie.get(query));
}
}
}