理解KMP算法及其复杂度估计

问题:判断一个字符串(str2 长度为m)是否是另一个字符串(str1 长度为n)的子序列。
方法一:暴力方法


从str1的第一个字符开始检测,若没有匹配成分,则向后移一位继续检测,直到str1的末尾。时间复杂度为O(nm)。

方法二:KMP法
1.记录str2中每个字符的前缀序列和后缀序列相同的最大值,将其放在next数组里
记录每个字符的前缀序列和后缀序列相同的最大值
例如next[0]=-1(规定首字符为-1),next[1]=0,next[2]=0,next[3]=0,next[4]=1,next[5]=2,next[6]=3
写next数组的代码如下:

public static int[] getNextArray(char[] str){
    if(str.length == 1){
        return new int[] {-1};
    }
    int[] next = new int[str.length];
    next[0] == -1;
    next[1] == 0;
    int i == 2;
    int cn == 0;
    while(i != str.length-1){
        if(str[i-1] == str[cn]){
            next[i++] == ++cn;
        }else if(cn>0){
            cn = next[cn];//cn往前跳到上一个最大前缀序列的后一个字符
        }else{
            next[i++] == 0;//cn调到0位置时
        }
    }
    return next;
}
            

next数组写完之后就可以写主函数了,主函数的代码如下:

public static int getIdexOf(String s1,String s2){
    if(s1 == null || s2 == null || s2.length<1 || s1.length<s2.length){
        return -1;
        }
    char[] str1 == s1.toCharArray();
    char[] str2 == s2.toCharArray();
    int[] next = getNextArray(str2);
    int i1 = 0;
    int i2 = 0;
    while(i1<str1.length && i2<str2.length){//注意不能越界
        if(str1[i1] == str[i2]){
            i1++;
            i2++;
        }else if(i2 != 0){
            i2 == next[i2];//往前调到上一个最大前缀的后一个字符
        }else{
            i1++;
        }
    return i2 == str2.length?i1-i2:-1;
}
    
            

时间复杂度为O(m+n)


版权声明:本文为a282608054原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。