weinan030416

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

kmp算法

 

复制代码
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<fstream> 
using namespace std;
int next[10];
void Next(char*T,int n)
{
   int i=1,j=0;
   next[1]=0;
   while(i<n)
   {
           if(j==0||T[i-1]==T[j-1])
           {
               i++,j++;
               next[i]=j;
        }
        else
        j=next[j];
   }
}

bool KMP(char * S,char * T,int l,int n)
{
    int i=1,j=1;
    while(i<=l&&j<=n)
    {
        if(j==0||S[i-1]==T[j-1])
        {
            i++;
            j++;
        }
        else
        {
            j=next[j];
        }
    }
   if(j>n)
   return true;
   return false;
}

int main() 
{
    int i=10;
    while(i--)
    {
        char a[1000],b[1000],c[1000]; 
        cin>>a;        cin>>b;//a模式串,b匹配串
        int n=strlen(a);
        int l=strlen(b);
        
        Next(a,n);//根据模式串T,初始化next数组
        for(int i=0;i<10;i++)
        cout<<next[i];
        if(KMP(b,a,l,n))
        {
            cout<<a<<"        "<<b<<"        "<<"Yes\n";
        }
        
        else
        {
            cout<<a<<"        "<<b<<"        "<<"No\n";
        }
    }
    
    return 0;    
}
复制代码

 

posted on   楠030416  阅读(15)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示