码迷,mamicode.com
首页 > 编程语言 > 详细

next数组修正版KMP算法

时间:2020-05-01 12:39:47      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:ext   nbsp   length   puts   style   ack   int   main   arch   

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算法

标签:ext   nbsp   length   puts   style   ack   int   main   arch   

原文地址:https://www.cnblogs.com/Jimmy-hacks/p/12813007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!