next数组修正版KMP算法

Posted jimmy-hacks

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了next数组修正版KMP算法相关的知识,希望对你有一定的参考价值。

public class Kmp {
    String snippet;
    String searchText;
    int[] next;

    public Kmp(String inputString) {
        this.snippet = inputString;
        // next = new int[this.snippet.length()];
    }

    public void setNext(String searchText){
        this.searchText = searchText;
        // String copySnippet = searchText;
        this.next = new int[searchText.length()];
        this.next[0]=-1;
        for(int frontIndex=0,backIndex=-1;frontIndex<searchText.length()-1;){
            if(backIndex==-1 || searchText.charAt(frontIndex)==searchText.charAt(backIndex)){
                frontIndex++;
                backIndex++;
                if(searchText.charAt(frontIndex)!=searchText.charAt(backIndex)){
                    this.next[frontIndex] = backIndex;
                }else{
                    this.next[frontIndex] = this.next[backIndex];
                }
            }else{
                backIndex = this.next[backIndex];
            }
        }
    }

    //从pos之后的位置搜索匹配字符串
    public int KmpSearch(int pos){
        int snippetIndex=pos;
        int searchTextIndex=-1;
        // int searchResultIndex=0;
        while(snippetIndex<this.snippet.length()&&searchTextIndex<this.searchText.length()){
            // searchResultIndex = snippetIndex;
            if(searchTextIndex==-1||this.snippet.charAt(snippetIndex)==this.searchText.charAt(searchTextIndex)){
                snippetIndex++;
                searchTextIndex++;
                // searchResultIndex = snippetIndex-searchTextIndex;
            }else{
                searchTextIndex = this.next[searchTextIndex];
            }
        }
        return searchTextIndex >= this.next.length? snippetIndex-this.searchText.length():-1;
    }

    public int KmpSearch(){
        return this.KmpSearch(0);
    }

    public static void main(String[] args) {
        Kmp instance = new Kmp("ababcabcacbab");
        instance.setNext("abc");
        int resultIndex = instance.KmpSearch();
        System.out.println(resultIndex);
    }
}

 

以上是关于next数组修正版KMP算法的主要内容,如果未能解决你的问题,请参考以下文章

字符串匹配KMP算法中Next[]数组和Nextval[]数组求法

字符串匹配KMP算法中Next[]数组和Nextval[]数组求法

数据结构—串KMP模式匹配算法

KMP算法模式匹配——手工求解next和nextval数组值

KMP算法模式匹配——手工求解next和nextval数组值

Kmp算法浅谈