KMP算法实现

KMP算法是一种改进的字符串匹配算法,KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,函数本身包含了模式串的局部匹配信息。

public static int searchKMP(String s1,String s2)
    {
        int i = 0;   //  主串的下标
        int j = 0;   //  子串的下标
        char[] x = s1.toCharArray();
        char[] y = s2.toCharArray();
        while (i<s1.length()&&j<s2.length()){
            if(j==-1||x[i]==y[j]){   // j==-1是子串第一个字母和主串不同时,i增加,j保持不变
                i++;
                j++;
            }else {
                j = next[j];
            }
        }

        if (j==s2.length()){
            return i-j;
        }else
            return -1;
    }

    public static void getNext(String p,int[] next)
    {
        int k = -1;
        int j = 0;
        char[] s = p.toCharArray();
        next[0] = -1;
        //因为在循环中下标先增加,再赋值,所以循环次数为字符串长度减一
        while (j<p.length()-1){
            if(s[k]==s[j] || k==-1){
                ++k;
                ++j;
                next[j] = k;
            }else {
                k = next[k];
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_39454351/article/details/85223135