KMP之:【KMP的三种匹配方式】【1.模式串前缀和主串后缀匹配】【2.模式串完全匹配在主串中】【3.模式串和主串一点都不匹配】

例题: 

 

 

 

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+10;
string str1,str2;
int ne[N];
int n,len;

void init(string p)
{
    for(int i=2,j=0;i<=n;i++)
    {
        while(j&&p[i]!=p[j+1])
        {
            j=ne[j];
        }
        if(p[i]==p[j+1])
        {
            j++;
        }
        
        ne[i]=j;
    }
}

int kmp(string p,string s)
{
    
    int  i,j;
    for( i=1,j=0;i<=len;i++)
    {
        while(j&&s[i]!=p[j+1])
        {
            j=ne[j];
        }
        if(s[i]==p[j+1])
        {
            j++;
        }
        
        if(j==n)
        {
            return i-n+1;   //返回第一个匹配的位置
        }
        
    }
    //如果不能完全匹配,就返回第一个
    return i-j;
    
}


int main()
{
    ios::sync_with_stdio(false);
	cin.tie(nullptr);
    cin>>str1>>str2;
    bool f1=false,f2=false;
    int len1=str1.size();
    int len2=str2.size();
    string s1,s2;
    s1=str1,s2=str2;
    str1=" "+str1;
    str2=" "+str2;
    
    //①str1是模式串,str2是主串
    n=len1;
    len=len2;
    init(str1);
    int pos=kmp(str1,str2);

    
    if(pos==n+1)
    {
        f1=true;
    }
    
    int l1;
    //如果是完全匹配
    if(pos+n-1<=len)
    {
        cout<<s2<<endl;
        return 0;
    }
    else  //否则是前缀和主串后缀匹配
    {
        l1=len-pos+1;
    }
    
    
    n=len2;
    len=len1;   //主串变成了第一个字符串 
    
    memset(ne,0,sizeof ne);
    init(str2);
    pos=kmp(str2,str1);
   
    
    if(pos==n+1)
    {
        f2=true;
        
        if(f1&&f2)
        {
            
            cout<<s1+s2<<endl;
            return 0;
        }
    }
    
    int l2;
    //如果完全匹配
    if(pos+n-1<=len)
    {
        cout<<s1<<endl;
        return 0;
    }
    else  //否则是前缀和主串后缀匹配
    {
        l2=len-pos+1;
    }
    
    
    if(l1>=l2)
    {
        cout<<s2;
        for(int i=l1+1;i<=len1;i++)
        {
            cout<<str1[i];
        }
        
        
        return 0;
    }
    else{
        cout<<s1;
        for(int i=l2+1;i<=len2;i++)
        {
            cout<<str2[i];
        }
    }
    
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值