字串变换(BFS,字符串处理)

在这里插入图片描述
在这里插入图片描述

每一个字符串可能存在可以使用同一种替换规则多次比如

初始串: aaa
变换规则:a→b

这种情况一个串可以三次使用变换规则,所以当我们find初始串是否存在可变换的子串时,每次查找一次将find()查找起始位置更新即可

这里有一个坑点:在我们需要改变原始字符串是,不能用替换,否则原始字符串改变会影响其他变换规则的变换,这里我们只能使用拼接压入队列中

#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<string,string>mp;
int main(){
	string A,B;
	string x[10],y[10];//记录起始,与结束的状态 
	cin>>A>>B; 
	int n=1;
	while(cin>>x[n]>>y[n]){//将规则存入数组当中 
		n++;
	}
	n--;
	queue<string>A0;//起始状态压入队列 
	queue<int>p;
	A0.push(A);
	p.push(0);
	while(!A0.empty()){
		//cout<<A0.front()<<p.front()<<endl;
		if(A0.front()==B){//当找到时输出 
			cout<<p.front();
			return 0; 
		}
		if(p.front()==10){//当次数大于10次直接弹出不需要继续搜索 
			A0.pop();
			p.pop();
		}
		string t=A0.front();;
	    if(mp.count(t)){//检测当前字符串有没有出现过 
	    	A0.pop();
	    	p.pop();
	    	continue;
	    }
	    mp[t]=1;
		for(int i=1;i<=n;i++){//依次按规则作出几种变换 
			int L=0;
			while(t.find(x[i],L)!=-1){//如果找得到 
				L=t.find(x[i],L);
				//A0.push(t.replace(L,x[i].length(),y[i]));
				A0.push(t.substr(0,L)+y[i]+t.substr(L+x[i].length()));//改变字符串压入队里中 
				p.push(p.front()+1);//次数加一 
				//cout<<t<<" "<<p.front()<<endl;
				L++;
			}
		} 
		A0.pop();//当前字符串完成了任务 
		p.pop();
	}
	printf("NO ANSWER!\n");

	return 0;
} 

我还有一种写法,将规则存成映射关系,但是只能AC百分之60的数据
希望有人指正

#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<set>
using namespace std;
int main(){
    string A,B;
    string x,y;
    cin>>A>>B;
    map<string,string>s;
    set<string>pp; 
    while(cin>>x>>y){
        s[x]=y;
    }
    queue<string>A0;
    queue<int>p;
    A0.push(A);
    p.push(0);
    while(!A0.empty()){
        if(A0.front()==B){//当找到时输出 
            cout<<p.front();
            return 0; 
        }
        if(p.front()>=10){
            A0.pop();
            p.pop();
        }
        int kai,len=0;
        string t=A0.front();
        if(pp.count(t)){
        	A0.pop();
        	p.pop();
        	continue;
        }
        pp.insert(t);
        map<string,string>::iterator it;
        for(it=s.begin();it!=s.end();it++){
            if(t.find(it->first,0)!=-1){
            	kai=t.find(it->first,0);
                len=it->first.size();
                //t.replace(kai,len,it->second);
                //cout << kai << len <<it->first<<" "<< it->second << endl;
                A0.push(t.substr(0,kai)+it->second+t.substr(kai+len));
                p.push(p.front()+1);
            }
        }
        A0.pop();
        p.pop();
    }
    printf("NO ANSWER!\n");
 
    return 0;
} 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值