如何将 NFA/DFA 转换为 Java?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7768759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:20:38  来源:igfitidea点击:

How to convert NFA/DFA to java?

javafinite-automataautomatastate-machine

提问by Inco Mob

I have a scenario where I have designed the NFA and using JFLAP I have converted it to DFA.

我有一个场景,我设计了 NFA 并使用 JFLAP 将其转换为 DFA。

I need to know, how to code it in Java?

我需要知道,如何用 Java 编码?

Basically how to implement those state transitions in Java. I have seen some examples which do this using switch and if statements, but I can't see any relation to DFA/NFA design and how to use it to implement in Java.

基本上如何在 Java 中实现这些状态转换。我已经看到一些使用 switch 和 if 语句执行此操作的示例,但是我看不到与 DFA/NFA 设计以及如何使用它在 Java 中实现的任何关系。

回答by ratchet freak

if you want to use a more object oriented design over while(true)switch(state){...}

如果你想使用更面向对象的设计而不是 while(true)switch(state){...}

public class State{
    private Map<Character,State> transitions=new HashMap<Character,State>();

    public void addTransition(char ch,State st){
        transitions.put(ch,st);
    }

    public State next(char ch){
        return transitions.get(ch);
    }

    private boolean fin=false;
    public boolean isFinal(){return fin;}
    public boolean setFinal(boolean f){fin=f;}        


}

and then the loop will be

然后循环将是

State currState=startState;
while(currState!=null && input.hasNextChar()){//you can also end directly when final state is reached
    char next = input.nextChar();//get next character
    currState = currState.next(next);
}

if(currState!=null && currState.isFinal()){
    // reached final state
}else{
    // to bad didn't match
}

回答by NPE

Take a look at dk.brics.automaton:

看看dk.brics.automaton

This Java package contains a DFA/NFA (finite-state automata) implementation with Unicode alphabet (UTF16) and support for the standard regular expression operations (concatenation, union, Kleene star) and a number of non-standard ones (intersection, complement, etc.)

这个 Java 包包含一个带有 Unicode 字母表 (UTF16) 的 DFA/NFA(有限状态自动机)实现,并支持标准正则表达式操作(连接、联合、Kleene 星)和许多非标准操作(交、补、等等。)

回答by RSS

Although you would have implemented it by now but there is very good implementation which is easy to digest. Use Digraph to maintain the epsilon transitions and stack to keep track of expressions. Check out this link from RS NFA.java .

虽然您现在已经实现了它,但有一个很好的实现,很容易理解。使用 Digraph 维护 epsilon 转换和堆栈以跟踪表达式。从 RS NFA.java查看此链接。