參考博客 https://www.cnblogs.com/AndyEvans/p/10240790.html
本節知識點是《編譯原理》第三章-詞法分析,學習參考教材為清華大學出版社《編譯原理》第三版:
前情提要:
字母表∑1和∑2的乘積( product):
∑1∑2 ={ab|a ∈∑1, b ∈ ∑2}
例: {0, 1} {a, b} ={0a, 0b, 1a, 1b}
字母表∑的n次冪( power):長度為n的符號串構成的集合
∑0 ={ ε }
∑n =∑n-1 ∑ , n ≥
例: {0, 1}3 ={0, 1} {0, 1} {0, 1}={000, 001, 010, 011, 100, 101, 110, 111}
字母表的正閉包(positive closure):長度正數的符號串構成的集合:
∑+ = ∑ ∪∑2 ∪∑3 ∪…
例:{a, b, c, d }+ = {a, b, c, d,aa, ab, ac, ad, ba, bb, bc, bd, …, aaa, aab, aac, aad, aba, abb, abc, …}
字母表的閉包(Kleene closure):任意符號串(長度可以為零)構成的集合:
∑* = ∑0 ∪∑+ = ∑0 ∪∑ ∪∑2 ∪∑3 ∪…
例:{a, b, c, d }* = {ε, a, b, c, d,aa, ab, ac, ad, ba, bb, bc, bd, …, aaa, aab, aac, aad, aba, abb, abc, …}
一、【 有窮自動機 】:
1、定義
有窮自動機 ( Finite Automata,FA )
具有一系列離散的輸入輸出信息和有窮數目的內部狀態(狀態:概括了對過去輸入信息處理的狀況)
2、FiniteAutomata的表示:
轉換圖 (Transition Graph)
結點:FA的狀態
初始狀態(開始狀態):只有一個,由start箭頭指向
終止狀態(接收狀態):可以有多個,用雙圈表示
帶標記的有向邊:如果對於輸入a,存在一個從狀態p到狀態q的轉換,就在p、q之間畫一條有向邊,並標記上a
3、Finite Automata定義(接收)的語言
給定輸入串x,如果存在一個對應於串x的從初始狀態到某個終止狀態的轉換序列,則稱串x被該FA接收
由一個有窮自動機M接收的所有串構成的集合A稱為是該FA定義(或接收)的語言,記為A=L(M (machine))
We say that M recognizes A.
A machine may accept several strings, but it always recognizes only one language.
4、最長子串匹配原則(Longest String Matching Principle )
·當輸入串的多個前綴與一個或多個模式匹配時,總是選擇最長的前綴進行匹配
·在到達某個終態之后,只要輸入帶上還有符號, DFA就繼續前進,以便尋找盡可能長的匹配
二、【 有窮自動機的分類 】:
確定的FA (Deterministic finite automata, DFA)
非確定的FA (Nondeterministic finite automata, NFA)
1、確定的有窮自動機DFA(Deterministic Finite Automata)
定義: (DFA (確定型有窮自動機)) A deterministic finite automaton (DFA) is a 5-tuple (Q,Σ,δ,q0,F)
where
1 Q is a finite set called the states,
2 Σ is a finite set called the alphabet,
3 δ : Q×Σ → Q is the transition function,
4 q0 ∈ Q is the start state,
5 F ⊆ Q is the set of accept states.
例子
注意F是集合
用轉換表表示DFA
M2和M3,兩個互為補集。Σ*=L(M2)+L(M3)
求一個自動機的補集:把終結狀態和非終結狀態互換
2、非確定的有窮自動機NFA(NonDeterministic Finite Automata)
定義 (NFA) A nondeterministic finite automaton (NFA) is a 5-tuple (Q,Σ,δ,q0,F)
where
1 Q is a finite set of states, 有窮狀態集
2 Σ is a finite alphabet, 輸入符號集合,即輸入字母表。假設ε不是Σ中的元素
3 δ : Q×Σε →P(Q) is the transition function,
4 q0 ∈ Q is the start state,
5 F ⊆ Q is the set of accept states.
P(Q) is the power set of Q
Σε = Σ∪{ε}
例子:
三、【 從正則表達式到有窮自動機 】
ε對應的NFA
□ 字母表Σ中符號a對應的NFA
□ r = r1r2對應的NFA
□ r = r1|r2對應的NFA
□ r = (r1)*對應的NFA
例:r=(a|b)*abb 對應的NFA