一、實驗題目:給定一個正規式 R = XY* | YX*Y | XYX ,請先在練習本上將此正規式轉變為NFA、DFA、最小化DFA;對你所完成的最小化DFA進行編程,完成詞法分析器工作。
二、設計分析:
1.將正規式轉變為NFA
2.再寫出轉換表
x | y | |
---|---|---|
A.{x} | {1,2,6,Y} | {3,4,5} |
B.{1,2,6,Y} | φ | {2,7,Y} |
C.{3,4,5} | {4,5} | {Y} |
D.{2,7,Y} | {Y} | {2,Y} |
E.{4,5} | {4,5} | {Y} |
F.{Y} | φ | φ |
G.{2,Y} | φ | {2,Y} |
3.根據轉換表畫出DFA
4.合並等價狀態
由上述轉換表可知C、E兩個狀態是等價的,可以合並,最小化DFA后可以得到六個狀態,重新標號為0→{A} , 1→{C,E} , 2→{B} , 3→{G} , 4→{D} , 5→{F}
5.最小化DFA為
三、程序代碼:
#include<iostream>
#include<string>
using namespace std;
//判斷字符串是否為正規文法
void judge(){
string s;
cout<<"請輸入一個字符串: ";
bool vis1=true;
cin>>s;
int len=s.size();
for(int i=0;i<len;i++){
if(s[i]!='x'&&s[i]!='y'){
cout<<"您輸入的格式有誤!"<<endl;
return;
}
}
if(s[0]=='x'&&len==1){
cout<<"屬於正規式R=xy*"<<endl;
return;
}else if(s[0]=='x'){
if(s[1]=='y'){
if(s[2]=='x'&&len==3){
cout<<"屬於正規式R=xyx"<<endl;
return;
}else{
for(int i=2;i<len;i++){
if(s[i]!='y'){
cout<<"不屬於正規式R"<<endl;
return;
}
}
cout<<"屬於正規式R=xy*"<<endl;
return;
}
}else{
cout<<"不屬於正規式R"<<endl;
return;
}
}else{
if(s[len-1]!='y'){
cout<<"不屬於正規式R"<<endl;
return;
}else{
for(int i=1;i<len-1;i++){
if(s[i]!='x'){
cout<<"不屬於正規式R"<<endl;
return;
}
}
cout<<"屬於正規文法R=yx*y"<<endl;
}
}
}
int main(){
judge();
return 0;
}