我需要创建具有字母表的 DFA:{a,b,c} 并且该字母表接受第一个和最后一个字母不同的单词。 即
“a” - Not Acceptable
“ab”- 可以接受
“aaa bb” - Not Acceptable
“cbba” - 可以接受
我首先尝试检查开头是否有“a”,但是出了问题,特别是如果我有 i.o. file.txt 中的“ab”或“ac”。
来源:
import java.io.*;
import java.util.ArrayList;
public class Task
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
BufferedReader reader = new BufferedReader(new FileReader("file.txt "));
ArrayList<String> wordList = new ArrayList<>();
String line = null;
while ((line = reader.readLine()) != null)
{
wordList.add(line);
}
for (String word : wordList)
{
if (word.matches("^a"))
{
if (word.matches("ab") || word.matches("^ac"))
{
System.out.print(word+" - OK\n");
}
else
{
System.out.print(word+" - STOP (word doesn't exists in alphabet)\n");
System.exit(0);
}
}
}
}
}
最佳答案
你的第一个“words.matches”将只匹配“a”,如果你想匹配所有以“a”开头的单词,然后是你想要的其他内容必须使用“^a.*”,其他匹配相同。
关于java - 确定性有限自动机 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366495/