您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 国内外标准规范 > 正规文法转换成正规式(C++)
#includeiostream#includeset#includemap#includestring#includealgorithmusingnamespacestd;multimapchar,stringproduction;setcharunFinal;setcharfinal;charS;voidInput(){charch;stringstr;cout非终结符(以0结尾):;while(cinch&&ch!='0')unFinal.insert(ch);cout终结符(以F结尾):;while(cinch&&ch!='F')final.insert(ch);cout开始符:;cinS;cout产生式(以00结尾):endl;while(cinchstr&&ch!='0')production.insert(make_pair(ch,str));}stringsolve(charch){stringstr(();stringre();stringch_1[8];stringstr1[8],str2[8];intlen,i,j,flag=10,strlen,sslen,lslen,num=0;multimapchar,string::iteratoriter=production.find(ch);intn=production.count(ch);for(i=0;in;i++,++iter){len=iter-second.size();str1[i].append(iter-second);str2[i]=str1[i];str2[i].replace(1,1,|);ch_1[i]=iter-second.substr(len-1);}for(i=0;in;i++)if(ch_1[i]=A&&ch_1[i]=Z){for(j=i+1;jn;j++)if(ch_1[i]==ch_1[j]){flag=i;str.push_back('(');str.append(str2[i].substr(0));str.append(str2[j].substr(0));for(;jn;j++){str1[j].assign(str1[j+1]);ch_1[j].assign(ch_1[j+1]);}}if(i==flag){strlen=str.size();str.replace(strlen-1,1,));str.append(ch_1[i]);str.push_back('|');}else{str.append(str1[i].substr(0));if(n=2)//相同左部产生式个数大于等于2个时,才输出|str.push_back('|');}}sslen=str.size();for(i=0;in;i++)if(ch_1[i]A||ch_1[i]Z)num++;if(num=2)str.push_back('(');for(i=0;in;i++)if(ch_1[i]A||ch_1[i]Z){str.append(ch_1[i]);if(i!=n-1)str.push_back('|');}if(num=2)str.push_back(')');lslen=str.size();for(inti=0;istr.size();i++){if(unFinal.find(str[i])!=unFinal.end())//str[i]是非终结符if(str[i]!=ch){//是其他非终结符re=solve(str[i]);str.replace(i,1,re);i+=re.size()-1;//下标后移Notice!}else{//此非终结符就是chstr.replace(i,1,*);str.replace(sslen-1,lslen-sslen+1,str.substr(sslen));}}str.push_back(')');returnstr;}intmain(){Input();coutendl输出正规式:;stringstr=solve(S);coutstr;coutendlendl;system(pause);return0;}
本文标题:正规文法转换成正规式(C++)
链接地址:https://www.777doc.com/doc-4874248 .html