KMP算法的实现

语言:C++

思想:1、使待匹配串每次获得最大的偏移量

            2、为了实现1,先得到一个对于待匹配串第一位的状态数组,表示下标[i]实现当前串向后滑动时的状态位置next[i]

            3、注意next[i]实际上只在待匹配串的i位置之前

            4、总的复杂度控制在o(n),其中n是source的规模

            5、关键要理解next状态向量组的构造,实际上就是求target中每一位及前连续的前置位和从target起始位置开始及其后连续位置(到位置j)为相同的串的位置j。

代码:

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

class KMPSolution {
public:
    // Must give two paras
    KMPSolution(string mSource, string mTarget) :
        source(mSource),target(mTarget), tSize(target.size()) {}
    void KMPMatch();
private:
    void displayInfo(auto iter, string name);
    void getNext();

    string source, target;
    int tSize;
    vector<int> next, result;
};

void KMPSolution::getNext() {
    int i = 0, j = -1;
    next.push_back(j);
    while(i < tSize) {
        while(j>=0 && target[i] != target[j])
            j = next[j];
        i++; j++;
        next.push_back(j);
    }
}

void KMPSolution::KMPMatch() {
    // Get the next array
    getNext();
    // Get the result
    int i = 0, j = 1, sourceSize = source.size();
    while (i < sourceSize) {
        while (j >=0 && source[i] != target[j])
            j = next[j];
        i++; j++;
        if (j == tSize) {
            result.push_back(i - j);
            j = next[j];
        }
    }
    // Display The result
    displayInfo(source, "Source");
    displayInfo(target, "Target");
    displayInfo(next, "next");
    displayInfo(result, "result");
}

void KMPSolution::displayInfo(auto iter, string name) {
    cout << "----------------------The " << name << " array------------------------" << endl;
    for (auto it = iter.begin(); it != iter.end(); it++)
        cout<<*it<<" ";
    cout<<endl;
    cout << "--------------------------------------------------------------" << endl;
    cout<<endl<<endl;
}

int main() {
    string source = "abcdefabcdefabcdefabcabcdkkljfabcdefabc";
    string target = "abcdefabc";
    KMPSolution kslo(source, target);
    kslo.KMPMatch();
    system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值