确定性有限自动机 - Java

Deterministic Finite Automaton - Java

我需要创建具有字母表的 DFA:{a,b,c} 并且该字母表接受第一个和最后一个字母不同的单词。 即

"a" - 不可接受

"ab" - 可以接受

"aaa bb" - 不可接受

"cbba" - 可以接受

我首先尝试检查开头是否有 "a",但有些地方不对劲,尤其是如果我有 i.o。 "ab" 或 "ac" 在 file.txt.

来源:

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[=15=”开头的所有单词]”然后是你必须使用的其他东西“^a.*”,其他比赛也是如此。