- int next[N];
- char str1[M],str2[N];
- //str1 长,str2 短
- //len1,len2,对应str1,str2的长
- void get_next(int len2)
- {
- int i = 0,j = -1;
- next[0] = -1;
- while(i<len2)
- {
- if(j == -1 || str2[i] == str2[j])
- {
- i++;
- j++;
- if(str2[i] != str2[j])
- next[i] = j;
- else
- next[i] = next[j];
- }
- else
- j = next[j];
- }
- //计算某字符串的周期,如aaaa是4,abcd是1
- /*
- int i = 0;j = -1;
- next[0] = -1;
- while(str2[i])
- {
- if(j == -1 || str2[i] == str2[j])
- {
- i++;j++;
- next[i] = j;
- }
- else
- j = next[j];
- }
- len = strlen(str);
- i = len-j;
- if(len%i==0)
- return len/i;
- else
- return 1;
- */
- }
- int kmp(int len1,int len2)
- {
- int i = 0,j = 0;
- get_next(len2);
- while(i<len1)
- {
- if(j == -1 || str1[i] == str2[j])
- {
- i++;
- j++
- }
- else
- j = next[j];
- /*
- if(j == len2)//计算str2在str1中出现多少次
- {
- cnt++;
- j= next[j];
- }
- */
- }
- //return j; //j为匹配的长度
- if(j>len2)
- return 1;//这里也可以返回i-len2来获得匹配在主串中开始的位置
- else
- return 0;
- }
- //数字KMP
- int a[1000005],b[10005];
- int next[10005],n,m;
- void getnext()
- {
- int i = 0,j = -1;
- next[0] = -1;
- while(i<m)
- {
- if(j == -1 || b[i] == b[j])
- {
- i++;
- j++;
- if(b[i] == b[j])
- next[i] = next[j];
- else
- next[i] = j;
- }
- else
- j = next[j];
- }
- }
- int kmp()//返回匹配位置
- {
- int i = 0,j = 0;
- while(i<n)
- {
- if(a[i] == b[j])
- {
- if(j == m-1)
- return i-j+1;
- i++;
- j++;
- }
- else
- {
- j = next[j];
- if(j == -1)
- {
- i++;
- j = 0;
- }
- }
- }
- return -1;
- }
【模板】KMP
最新推荐文章于 2020-12-03 10:38:14 发布