码迷,mamicode.com
首页 > 其他好文 > 详细

DS串应用--串替换

时间:2020-01-11 20:35:50      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:fir   bst   ++   tin   data   长度   ima   include   else   

题目描述

给出主串、模式串、替换串,用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 *getnext(string p)
{
    int j=0,k=-1;
    int *next=new int[p.size()];
    next[0]=-1;
    while(j<(int)p.size()-1)
    {
        if(k==-1||p[j]==p[k])
        {
            j++;
            k++;
            next[j]=k;
        }
        else
            k=next[k];
    }
    return next;
}
 
int KMP(string s,string p)
{
    int i=0,j=0;
    int *next=getnext(p);
    while(i<(int)s.size()&&j<(int)p.size())
    {
        if(j==-1||s[i]==p[j])
        {
            i++;
            j++;
        }
        else
            j=next[j];
    }
    if(j==(int)p.size())
        return i-j+1;
    return -1;
}
 
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        string s,p,Replace;
        cin>>s>>p>>Replace;
        int slength=s.size();
        int plength=p.size();
        int firstindex=KMP(s,p);
        cout<<s<<endl;
        if(firstindex==-1)
            cout<<s<<endl;
        else
        {
            string result=s.substr(0,firstindex-1);
            string after=s.substr(firstindex-1+plength,slength);
            result+=Replace;
            result+=after;
            cout<<result<<endl;
        }
    }
    return 0;
}

 

DS串应用--串替换

标签:fir   bst   ++   tin   data   长度   ima   include   else   

原文地址:https://www.cnblogs.com/SZU-DS-wys/p/12180748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!