dfa模拟程序Java实现
时间: 2023-07-28 14:06:24 浏览: 95
DFA模拟程序
下面是一个简单的 DFA 模拟程序的 Java 实现:
```java
import java.util.*;
public class DFASimulator {
private int[][] transitions;
private int startState;
private Set<Integer> acceptingStates;
public DFASimulator(int[][] transitions, int startState, Set<Integer> acceptingStates) {
this.transitions = transitions;
this.startState = startState;
this.acceptingStates = acceptingStates;
}
public boolean accepts(String input) {
int currentState = startState;
for (char c : input.toCharArray()) {
currentState = transitions[currentState][c - 'a'];
}
return acceptingStates.contains(currentState);
}
public static void main(String[] args) {
// Example DFA that accepts strings containing "ab"
int[][] transitions = {
{1, 0},
{1, 2},
{3, 0},
{3, 3}
};
int startState = 0;
Set<Integer> acceptingStates = new HashSet<>(Arrays.asList(1, 3));
DFASimulator dfa = new DFASimulator(transitions, startState, acceptingStates);
// Test the DFA
System.out.println(dfa.accepts("a")); // false
System.out.println(dfa.accepts("b")); // false
System.out.println(dfa.accepts("ab")); // true
System.out.println(dfa.accepts("ba")); // false
System.out.println(dfa.accepts("abc")); // true (accepts "ab" and ignores "c")
}
}
```
在这个例子中,我们创建了一个 DFA,它接受包含字符串 "ab" 的任何输入。我们可以使用 `DFASimulator` 类的 `accepts` 方法测试输入是否被 DFA 接受。在这个例子中,我们测试了几个字符串,并打印出了结果。
阅读全文