串替换

题目描述

给出主串、模式串、替换串,用KMP算法找出模式串在主串的位置,然后用替换串的字符替换掉模式串

本题只考虑一处替换的情况,如果你想做的完美一些,能够实现多处替换那

可能需要考虑模式串和替换串长度不一致的情况

输入

 

第一个输入t,表示有t个实例

第二行输入第1个实例的主串,第三行输入第1个实例的模式串,第四行输入第1个实例的替换串

以此类推

 

输出

第一行输出第1个实例的主串

第二行输出第1个实例的主串替换后结果,如果没有发生替换就输出主串原来的内容。

以此类推

样例输入

3 aabbccdd bb ff aaabbbccc ddd eee abcdef abc ccccc

样例输出

aabbccdd aaffccdd aaabbbccc aaabbbccc abcdef cccccdef

 

#include <iostream>
#include <string>

using namespace std;

int *get_next(string s)
{
    int *n=new int[s.length()];
    n[0]=-1;
    int i,j;
    i=0;
    j=-1;
    while(i<s.length()-1)
    {
        if(j==-1 || s[i]==s[j])
        {
            i++;
            j++;
            n[i]=j;
        }
        else
            j=n[j];
    }
    return n;
}
int KMP(string s,string key)
{
    int *n=get_next(key);

    int i=0,j=0;
    int s_l=s.length(),j_l=key.length();
    while(i<s_l && j<j_l)
    {
        if(j==-1 || s[i]==key[j])
        {
            i++;
            j++;
        }
        else
        {
            j=n[j];
        }
    }
    if(j==key.length())
        return i-key.length()+1;
    else
        return 0;
}

int main()
{
    string s,key,rekey;
    int *n;
    int t,temp;
    cin>>t;
    while(t--)
    {
        cin>>s>>key>>rekey;
        cout<<s<<endl;
        temp=KMP(s,key);
        if(temp==0)
            cout<<s<<endl;
        else
        {
            s.erase(temp-1,key.size());
            s.insert(temp-1,rekey);
            cout<<s<<endl;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值