蛮力法解决字符串匹配问题

蛮力法解决字符串匹配问题

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

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

using namespace std;

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

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

    double sum = 0;
    int bf;

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

        bf = BF(S,T);

        QueryPerformanceCounter(&nEndTime);

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

    double avgTime = sum/200.0;

    cout << "Result: " << bf << endl;
    cout << "The average time of BF is " << avgTime;

    return 0;
}

猜你喜欢

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