1 KMP算法

#include "pch.h"
#include <iostream>
#include <vector>
#include <string>

void get_next(const std::string& T, std::vector<int>& next) {
    int Tlen = T.size();
    next.resize(Tlen);
    next[0] = -1;
    int k = -1;
    int j = 0;
    while (j < Tlen - 1) {
        //T[k]表示前缀,T[j]表示后缀
        if (k == -1 || T[k] == T[j]) {
            ++k;
            ++j;
            next[j] = k;
        }
        else
            k = next[k];
    }
}

//KMP算法 
int KMP_search(const std::string& S, const std::string& T) {
    if (T.empty())
        return 0;
    int i = 0, j = 0;
    int sLen = S.size();
    int tLen = T.size();
    std::vector<int> next;
    get_next(T, next);
    while (i < sLen && j < tLen){
        //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++    
        if (j == -1 || S[i] == T[j]) {
            i++;
            j++;
        }
        else{
            //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]    
            //next[j]即为j所对应的next值      
            j = next[j];
        }
    }
    if (j == tLen)
        return i - j;
    return -1;
}


int main() {
	std::string S = "BBC ABCDAB ABCDABCDABDE";
	std::string T = "ABCDABD";
	
	int k = KMP_search(S, T);
	if (k != -1) {
		std::cout << S << std::endl;
		for (int i = 0; i < k; ++i)
			std::cout << " ";
		std::cout << T << std::endl;
	}
	else
		std::cout << "Con't find " << T << " in " << S << std::endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40843865/article/details/89221628