字符串匹配KMP算法( 二 )

/**s:主串slen:主串长度p:模式串plen:模式串长度next:已经计算过的next数组res:匹配的下标位置**/int kmp(char*s , int slen, char*p, int plen, int *next, int *res){int s_index, p_index=0, res_index=0;for(s_index = 0; s_index < slen; s_index++){while(p_index > 0 && s[s_index] != p[p_index]){//下一个匹配位为next数组的第j-1位p_index = next[p_index-1]+1;}if(s[s_index] == p[p_index]){p_index ++;//如果相等就都往后移一位}//如果匹配串的第一位一直和模式串第一位不相等,那么模式串id s_index一直往后移if(p_index == plen){res[res_index++] = s_index-p_index+1;//应为当模式串和匹配串相等时,匹配串的下标会加1,所以会多减1,后面要加上p_index = 0;}}return res_index;} 
说明: 以上仅仅代表自己的想法 。




推荐阅读