HDU 2594 数据结构之KMP

来源:互联网 发布:花呗怎么在淘宝买东西 编辑:程序博客网 时间:2024/05/20 14:25

点击打开链接

题意:两个串,求第一个串开头,第二个串的匹配的最长长度

思路:将两个串合并,合并后的长度为len,求出KMP的next数组,next[len]代表的就是后面与前面的匹配程度,说白了就是匹配的位置,然后讨论处理一下

#include <iostream>#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>using namespace std;typedef long long ll;const int inf=0x3f3f3f3f;const int maxn=100010;const int mod=10007;char str1[maxn],str2[maxn];int Next[maxn];void makenext(int m){    int i=0,j=-1;    Next[i]=-1;    while(i<m){        if(j==-1||str1[i]==str1[j])            Next[++i]=++j;        else j=Next[j];    }}//int KMP(int n,int m){//    int i=0,j=0,ans=0;//    while(i<n){//        if(j==-1||str2[i]==str1[j]) i++,j++;//        else j=Next[j];//        if(j==m){//            ans++;j=Next[j-1];i--;//        }//    }//    return ans;//}int main(){    while(scanf("%s%s",str1,str2)!=-1){        int len1=strlen(str1);        int len2=strlen(str2);        strcat(str1,str2);        int len=strlen(str1);        makenext(len);        int ans=Next[len];        if(ans==0) printf("0\n");        else if(ans>=len1||ans>=len2){            if(len1<len2){                for(int i=0;i<len1;i++) printf("%c",str1[i]);                printf(" %d\n",len1);            }else{                printf("%s %d\n",str2,len2);            }        }else{            for(int i=0;i<ans;i++) printf("%c",str1[i]);            printf(" %d\n",ans);        }    }    return 0;}

0 0