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);
    }
}

猜你喜欢

转载自www.cnblogs.com/Jimmy-hacks/p/12813007.html