KMP pattern matching algorithm (java achieve)

Bowen use Java to achieve the KMP pattern matching algorithm
attach ultra-detailed explanation of the great God: KMP algorithm is explained in detail

 	/*
    * KMP算法
    *
    * */
    private int[] getNextVal(IString T){
        int [] nextVal = new int[T.length()];
        int j = 0;
        int k = -1;
        nextVal[0] = -1;
        while (j<T.length()-1){
            if (k == -1||T.charAt(j) == T.charAt(k)){
                j++;
                k++;
                if (T.charAt(j) != T.charAt(k))
                    nextVal[j] = k;
                else
                    nextVal[j] = nextVal[k];
            }else
                k = nextVal[k];
        }
        return nextVal;
    }

    public int index_KPM(IString T,int start){
        int [] next = getNextVal(T);//计算模式串next[]函数值
        int i = start;//主串指针
        int j = 0;//模式串指针
        //对两串从左到右逐个比较字符
        while (i<this.length()&& j<T.length()){
            if (j == -1||this.charAt(i)==T.charAt(j)){
                i++;
                j++;
            }else {
                j = next[j];//模式串右移
            }
        }
        if (j<T.length()){
            return -1;
        }else {
            return (i-T.length());//匹配成功
        }
    }
Published 34 original articles · won praise 65 · views 3735

Guess you like

Origin blog.csdn.net/baidu_41860619/article/details/103567589
Recommended