【转载】从头到尾彻底理解KMP算法

1、引言

①字符串匹配,暴力时间复杂度O(N*M),一旦发生匹配失败,S串和T串都要回退到起点,重新开始一轮匹配。

int ViolentMatch(char* s, char* t)
{
    int sLen = strlen(s);
    int tLen = strlen(t);
    for(int i=0;i<sLen;i++){           //S串
        int j=0;
        for(;j<tLen;j++){              //T串
            if(s[i+j]!=t[j]) break;   //匹配失败
        }
        if(j==tLen) return i;        //匹配完全
    }
    return -1;
}

暴露问题:一旦发生失败,S串和T串都需要回退到起始匹配点。有什么方法可以只让T串回退,S串不回退?KMP应用而生。

②KMP时间复杂度O(N+M)

思路:每次匹配失败,能不能不回退,S串不回退,T串回退到最大前缀,引入next数组。

参考:https://blog.csdn.net/wardseptember/article/details/78801491

猜你喜欢

转载自www.cnblogs.com/IIYMGF/p/11400053.html