标签:
KMP 是经典的用于字符串模式匹配,可以大幅度减少匹配的次数
其核心重点在于 next 数组的获取
// next 数组 void getnext(string s, int n, int *next){ next[0] = -1; int i = 0, j = -1; while(i< n){ if(j == -1 || s[i] == s[j]){ i++, j++; next[i] = j; } else j = next[j]; } } // next 数组 void getnext(string s, int n, int *next){ int i = 0, j = -1; next[0] = j; while(i< n){ while(j != -1 && s[j] != s[i]) j = next[j]; i++, j++; if(j >= n) next[i] = next[j-1]; else next[i] = j; } } void kmp(string s1, int n, string s2, int m){ int next[1000005]; getnext(s1, n, next); int i = 0, j = 0; int count = 0; while(i< m){ while(j != -1 && s1[j] != s2[i]) j = next[j]; i++, j++; if(j == n){ count++; j = next[j]; } } cout << count << endl; }
就一般而言,并不会让你直接用 KMP 对字符串进行匹配, 而是使用其 next 数组用于其他问题的求解
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://www.cnblogs.com/ygdblogs/p/5373126.html