KMP字符串查找算法

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

void get_next(char *str,int *num)
{
    int idFront = 0;
    int len = strlen(str);
    int amount = 1;
    int flag = 0;//相等时一直往下循环
    int flag2 = 0;//标记是否在循环过程中不匹配,如果在循环过程中不匹配,则要防止跳过这个数

    for(int i = 2;i<len;i++)
    {
        do
        {
            if(str[i-1] == str[idFront])
            {
                flag2 = 1;
                num[i] = ++amount;
                flag = 1;//保证相等就会循环一直循环到不等
                i++;
                idFront++;
            }
            else
            {
                if(flag2 == 1)//保证在相等循环时最后一个不匹配,然后再与第0个进行比较,避免外层for循环跳过这个不匹配的数
                {
                    i--;
                }
                flag2 = 0;
                flag = 0;
                idFront = 0;
                amount = 1;
            }
        }while(flag == 1);
    }
}

void find(char *str,char *substr)
{
    int *next = new int[strlen(substr)];
    for(int p=0;p<strlen(substr);p++)
    {
        next[p] = 1;
    }
    next[0] = 0;

    get_next(substr,next);

    int i=0;//i不会回溯
    int j=0;
    int count = 1;
    while(i<strlen(str) && j < strlen(substr))
    {
        cout << "" << count++ << "次比较,i = " << i << "   j = " << j ;
        
        if(str[i] == substr[j])
        {
            cout << "      相等  " << endl;
            system("pause");
            i++;
            j++;
        }
        else
        {
            cout << "      不相等  " << endl;
            system("pause");
            if(j>0)
            {
                j = next[j] - 1;//下一次i与j比较的位置,可以在纸上画出来然后找出关系
            }
            else
            {
                j = 0;
                i++;
            }
        }
    }

    int len = strlen(substr);
    if(j == len)
    {
        cout << "找到,位置为" << i-strlen(substr) << endl;
    }
    else
    {
        cout << "没找到" << endl;
    }
}

void main()
{
    char *str = "abcdabcdabcdabceabcdabcabcdadewerwq";
    char *substr = "abcdabce";
    cout << str << endl;
    cout << substr << endl;
    find(str,substr);
}
原文地址:https://www.cnblogs.com/xiaochi/p/5055791.html