/** nt[i]的代表以0...i的最长公共前缀后缀 即:0...nt[i] == i-nt[i]...i **/ int nt[MAXN]; /**nt[]数组的取得 如果没有符合的公共前后缀 nt[i]=-1; 如果nt[i]=k; s[i+1] = s[k+1] nt[i] = k+1; **/ void Get_Next(char* s){ nt[0] = -1; int k = nt[0]; int len_s = strlen(s); for(int i = 0;i < len_s-1;i ++){ while(s[i+1] != s[k+1] && k != -1) k = nt[k]; if(k != -1) k++; else if(k == -1 && s[i+1] == s[k+1]) k++; nt[i+1] = k; } } /** p为模式串 **/ bool KMP_Match(char* s,char* p){ int k = -1;///这里应该是-1,上次写好像搞错了 int len_s = strlen(s),len_p = strlen(p); for(int i = 0;i < len_s;i ++){ while(s[i] != p[k+1] && k != -1) k = nt[k]; if(k != -1) k++; else if(k == -1 && s[i] == p[k+1]) k++; if(k == len_p-1) return true; } return false; }