使用KMP算法求解字符串匹配问题C++代码

使用KMP算法求解字符串匹配问题

以下代码使用kmp算法实现字符串S和T匹配,并统计了代码运行时间。

#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <iomanip>

using namespace std;

void GetNext(char T[], int next[]){	//求取next值
    next[0] = -1;
    int j=1, k=0;
    while(T[j] != '\0')     //字符串未遍历完
        if((k==0) || (T[j]==T[k])){
            next[j] = k;
			j++;
            k++;
        }
        else
            k = next[k];
}

int KMP(char S[], char T[]){
    int i=0,j=0;
    int next[5]={0};
    GetNext(T,next);

    while((S[i] != '\0') && (T[j] != '\0')){
        if(S[i] == T[j]){
            i++;
            j++;
        }
        else {
            j = next[j];
            if(j==-1){
                i++;
                j++;
            }
        }
    }
    if(T[j] == '\0')
        return (i-strlen(T)+1);
    else
        return 0;
}

int main()
{
    LARGE_INTEGER nFreq;
    LARGE_INTEGER nBeginTime;
    LARGE_INTEGER nEndTime;
    double time;
    QueryPerformanceFrequency(&nFreq);

    double sum = 0;
    int kmp;
    for(int i=0; i<200; i++){
        QueryPerformanceCounter(&nBeginTime);
        char S[] = "ababcabccabcacbab";
        char T[] = "abcac";
        kmp = KMP(S,T);

        QueryPerformanceCounter(&nEndTime);

        time = (double)(nEndTime.QuadPart-nBeginTime.QuadPart)*1000000000/(double)(nFreq.QuadPart);
        sum = sum+time;
    }

    double avgTime = sum/200.0;
    cout << "Result: " << kmp << endl;
    cout << "The average time of KMP is " << avgTime;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44880708/article/details/106228320