自动机用于前缀匹配

时间:2017-02-11 13:36:28

标签: java finite-automata nfa automaton finite-state-automaton

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

例如:从字符串[“lucene”,“lucid”]创建的自动机,当给出“luc”或“luce”时匹配,但在给出“lucy”或“清醒梦”时不匹配

1 个答案:

答案 0 :(得分: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);
    }
相关问题