2017-02-11 69 views
-2

使用开源的Java自动机库,例如:org.apache.lucene.util.automaton或dk.brics.automaton,如何构建用于前缀匹配的自动机?用于前缀匹配的自动机

例如:由字符串集合[“lucene”,“lucid”]创建的自动机,当给定“luc”或“luce”时将匹配,但当给出“lucy”或“lucid dream” ”。

+0

这正是如何[特里结构(HTTPS://en.wikipedia。 org/wiki/Trie)的作品。类似的想法可以用来构造自动机。 “输入结束”字符的使用可能也很有用 - 比如'$'。 – Obicere

+0

我对尝试很熟悉,尽管我在Java中找到的实现(例如:PatriciaTrie)实际上是Maps,并且会返回与前缀关联的值。我只想检查是否存在前缀。 – tukushan

回答

0

前缀匹配可能使用org.apache.lucene.util.automaton通过设置所有状态接受,例如:

String[] strings = new String[]{"lucene", "lucid dream"}; 
    final List<BytesRef> terms = new ArrayList<>(); 
    for(String s : strings) { 
     terms.add(new BytesRef(s)); 
    } 
    Collections.sort(terms); 
    final Automaton a = DaciukMihovAutomatonBuilder.build(terms); 

    for (int i = 0; i < a.getNumStates(); i++) { 
     a.setAccept(i, true); 
    }