KMP算法解决字符串出现次数

比如主串为:”1001110110”
子串为:”11“
则出现位置分别为:3 4 7

//KMP算法 2015.6.7

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{   
    char *s = "1001110110";
    char *p = "11";
    int ar[20] = { 0 };
    //next
    ar[0] =-1;
    int i = 0,l=-1;
    while (i < strlen(p)-1)  //next函数
    {
        if (l==-1||p[i] == p[l])
        {
            i++; l++;   
            ar[i] = l;
        }
        else
            l = ar[l];  
    }
    int m=0, n=0;
    while (m < strlen(s)) //根据next判断是否匹配
    {
        if (n==-1||s[m] == p[n])
        {
            m++; n++;
        }
        else n = ar[n];
        if (n == strlen(p))
        {
            cout << m - strlen(p) << endl;
            n == 0;
            m -= strlen(p)-1;
        }

    }
    system("pause");
    return 0;
}
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/a781558066/article/details/46508783
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞