[英]Fastest way to lookup pattern matching words in java
给定一个总字数在 100,000-500,000 之间的字典,查找模式/掩码的最快方法是什么? 其中 '-' 是一个未知的字母,即 s--t- 将返回盐、咸、粪、苏格兰等......
目前使用的 trie 非常适合填充首字母的单词,但是当存在诸如 ---st 或 -tr- 之类的模式时,trie 的好处就完全丧失了。
我正在搜索的单词的分布基本上是均匀分布的,其中填充了第一个字母,而那些没有填充。
将单词加载到 SQL 数据库中然后使用 SQL 通配符搜索功能是否有意义? 或者我只是手动搜索每个可能的字母组合以获得空白字母的哈希图怎么样?
希望您能提供任何见解。
下面的小方法利用String#matches()方法以及动态创建的正则表达式,该正则表达式基于搜索条件字符串中提供的通配符。 它将返回一个字符串列表( List<String>
),其中包含找到的与提供的条件字符串匹配的任何单词。
我通过(使用BufferedReader(FileReader) )运行搜索条件字符串( "s--t-"
)的单词列表文件包含 370,108 个单词,通常在大约 250 毫秒或 0.25 秒(平均)内完成任务。
对于通配符,最常用的通配符是星号 ( * ),通常表示字符串中的零个或多个字符,以及问号 ( ? ),通常表示任何一个字符。 您显然想使用连字符 (-) 代替通常的问号,这是可以的。 提供的方法可以根据您的特定目的处理同一条件字符串中的所有三种通配符类型( * 、 ?和- )。
public static List<String> searchForWord(String dictionaryFilePath,
String searchCriteria) {
// This method ignores letter case!
List<String> foundList = new ArrayList<>(); // To hold all found words.
// Convert the supplied criteria string to a Regular Expression
// for the String#matches() method located in the 'while' loop.
String regEx = searchCriteria.replace("?", ".").replace("-", ".").replace("*", ".*?").toLowerCase();
// 'Try With Resources' use here to auto-close the reader.
try (BufferedReader reader = new BufferedReader(new FileReader(dictionaryFilePath))) {
String line = "";
while ((line = reader.readLine()) != null) {
line = line.trim().toLowerCase();
if (line.matches(regEx)) {
foundList.add(line); // There's a match...add to the List.
}
}
}
// catch Exceptions (if any).
catch (FileNotFoundException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
return foundList; // Return the List.
}
要使用此方法:
List<String> list = searchForWord("WordFile.txt", "s--t-");
for (String str : list) {
System.out.println(str);
}
从我使用的单词列表中找到的匹配项:
saeta saite saith sakti salta
salts salty santa santo santy
saute sauty scats scatt scote
scots scott scuta scute scuts
scyth seats sects seity senti
sents septa septi septs serta
sesti sexto sexts sheth shita
shits shote shots shott shute
shuts sidth sifts silts silty
sinto sintu sitta sixte sixth
sixty skate skats skete skite
skits skyte slate slath slats
slaty slete slite slits slote
sloth slots sluts smeth smite
smith smote smuts smyth snath
snite snits snitz snots softa
softs softy sooth soots sooty
sorts sorty south sowte spate
spath spats spete spite spits
spitz spots sputa spute sruti
state stats stets stite stith
stott suets suety suite suits
suity sutta swath swati swats
swith swots syftn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.