Any foo can do it(与词法分析相关的一个asm题)

来源:互联网 发布:mac打不开exe文件 编辑:程序博客网 时间:2024/06/05 05:00
注:当开头或末尾是不带逗号的集合时,此算法不能很好的分辩,讨论情况太复杂,故此题还是得另觅他法。
题目大致如下:输入"{"   和  ","  和  "}"三个字符组成的字符串来判断是否是一个集合的表达式。
Sample Input
4
{}
{{}}
{{}},{,}}
{,,}

Sample Output
Word #1: Set
Word #2: Set
Word #3: Set
Word #4: No Set

和词法分析程序有点象,如果用正则表达式,任务就轻松多了。当然那样子就没什么意思了,别人设计C++支持正则表达式也一件多么不容易的事情啊,等emacs弄熟了之后,要好好看看boost库中关于此的设计。自己写的是多么的蹩脚哦(程序尚不完善,有待调试,贴出来只为存档,现在饿了,吃饭去~):
思路:(1)先考虑由该三字符构成的最简单的集合有8个:{},{{},{}},{,},{{,}},{{,,},{},,},{{,},,}
               (2)任何复杂的集合最终都是由上面这8个集合单元构成的,所以把它们都用s替换(考虑到后面的单元里面包含前面的单元,长度长的优先开始替换).
               (3)替换后的就可以轻易的识别{s,.....}这样的子集合了.把经过(2)替换后得到的字符串搜索一遍,一找到s就看是否存在{s,...}形式的子集合,否则结果为no set.是则用s再替换该子集合。反复执行此过程,知道结果为no set或最后只剩下s.

//Any foo can do it
#include <iostream>
#include 
<string>
#include 
<cstddef>
using namespace std;
const string s
="s";

string
& replaceAll(string& context,const string& from,const string& to)
{
    size_t lookhere
=0;
    size_t foundhere;
    
while((foundhere=context.find(from,lookhere))!=string::npos){
    context.replace(foundhere,from.size(),to);
    lookhere
=foundhere+to.size();
    }

    
return context;    
}


void replace1(string& context)
{
    replaceAll(context,
"{{,},,}",s);
    replaceAll(context,
"{{,,,}}",s);
    replaceAll(context,
"{},{,,}",s);
    replaceAll(context,
"{},,,{}",s);
    replaceAll(context,
"{,,{,}}",s);

    replaceAll(context,
"{,,},{}",s);  
    replaceAll(context,
"{{,}}",s);
    replaceAll(context,
"{},{}",s);
    replaceAll(context,
"{{,,}",s);
    replaceAll(context,
"{,,{}",s);
    replaceAll(context,
"{},,}",s);
    replaceAll(context,
"{,,}}",s);
    replaceAll(context,
"{{}",s);
    replaceAll(context,
"{}}",s);
    replaceAll(context,
"{,}",s);
    replaceAll(context,
"{}",s);
}


bool replaceSubset(string
& context,size_t& where)
{
    
if(where<1return false;
    size_t headhere
=where-1;
    
if(context.at(headhere)!='{'return false;
    
else{
    
++where;
    
while(context.at(where)==',' && where<context.length()-2){
        
++where;
        
if(context.at(where)=='s'++where;
        
else return false;
    }

    
if(context.at(where)!='}'return false;
       
else{
           context.replace(headhere,where,s);
           
return true;
       }

    }

}


bool replace2(string
& context)
{
    
while(context!=s){
    size_t lookhere
=0;
    size_t foundhere
=context.find(s,lookhere);
    
while((foundhere=context.find(s,lookhere))!=string::npos){
        
if(!replaceSubset(context,foundhere)) return false;
        lookhere
=foundhere+1;
    }

    }

    
if(context==s) return true;
    
else return false;
}


bool isSet(string str)
{
    replace1(str);
    
return replace2(str);
}


int main()
{
    
int num;
    cin
>>num;
    string str[
10];
    
for(int i=0;i<num;i++) cin>>str[i];
    
for(int i=0;i<num;i++){
    
if(isSet(str[i])) cout<<"Word #"<<i+1<<":Set"<<endl;
    
else cout<<"Word #"<<i+1<<":No Set"<<endl;
    }

}

 

原创粉丝点击