KMP字符串匹配,字串

来源:互联网 发布:二分查找java 编辑:程序博客网 时间:2024/05/16 06:50


题意:输入多组,判断str2是否是str1的字串,是则输出串1在串2中的位置,否则输出-1;

  1. //当主串中第i个字符与模式中第j个字符“失配”时,  
  2. //主串中第i个字符应该与模式中哪个字符再比较。  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <string.h>  
  6. char str1[1000000],str2[1000000];  
  7. int next[1000000];  
  8. void getnext(int t)//next[j]表示当模式中第j个字符与主串中相应字符“失配”时,在模式中需要重新和主串中该字符进行比较的字符的位置。  
  9. {  
  10.     int i,j;  
  11.     i=1;j=0;next[i]=0;  
  12.     while(i<=t)  
  13.     {  
  14.         if(j==0||str2[i-1]==str2[j-1])  
  15.         {  
  16.             i++;j++;  
  17.             next[i]=j;  
  18.         }  
  19.         else  
  20.             j=next[j];  
  21.     }  
  22. }  
  23. int KMP(int s,int t)  
  24. {  
  25.     int i,j;  
  26.     i=1;j=1;  
  27.     while(i<=s&&j<=t)  
  28.     {  
  29.         if(j==0||str1[i-1]==str2[j-1])  
  30.         {  
  31.             i++;j++;  
  32.         }  
  33.         else  
  34.             j=next[j];  
  35.     }  
  36.     if(j>t)  
  37.         return (i-t);  
  38.     else  
  39.         return -1;  
  40. }  
  41. int main()  
  42. {  
  43.     int s,t,g;  
  44.    while(~scanf("%s%s",str1,str2))  
  45.    {  
  46.     s=strlen(str1);  
  47.     t=strlen(str2);  
  48.     getnext(t);  
  49.     g=KMP(s,t);  
  50.     printf("%d\n",g);  
  51.    }  
  52.     return 0;  
  53. }   
  54.   

0 0
原创粉丝点击