KMP算法

来源:互联网 发布:淘宝店铺如何激活 编辑:程序博客网 时间:2024/06/06 04:57

KMP看了网上很多博文,也看的不是很懂,最后看了这个视频教学,慢慢去理解终于弄懂了~~~挺好的教学。

http://v.youku.com/v_show/id_XNjg0OTk1MTc2.html?from=y1.2-1-87.3.1-2.1-1-1-0


下面是参照视频写的代码,以下为 hihocoder 1015的AC代码:

#include <iostream>#include <cstring>#include <string>using namespace std;int _next[10005];void getNext(const string& T){memset(_next , 0 , sizeof(_next));_next[0] = -1 ;int len = T.size();int i = 0,j = -1 ;  // j 前缀, i 后缀while(i < len){if(-1 == j || T[i] == T[j]){i++,j++;//_next[i] = j ;if(T[i] != T[j])   //对上一句的优化 {_next[i] = j ;}else{_next[i] = _next[j];} }else{j = _next[j];}} }int KMP(const string& s ,const string& T){int i = 0,j = 0 ;  //i 为原串指针, j 为模式串指针int len = s.size();int limit = T.size();int ans = 0 ;while(i < len){if(-1 == j || s[i] == T[j]){i++,j++;}else{j = _next[j];}if(j == limit){ans++; j = _next[j];}} return ans ;}int main(){string s , t ;int n ;cin >> n ;while(n--){cin >> t >> s ;getNext( t );cout << KMP(s , t) << endl ;}}


0 0