KMP

原理:http://blog.csdn.net/v_july_v/article/details/7041827

讲的只有最详细没有更详细的了

public class KMPTest {    
    public String originStr = null;
    public String moduleStr = null;
    public int[] next = null;      
    
    public int[] GetNext(String p){
        int[] next = new int[p.length()];
        next[0] = -1;  
        int k = -1;  
        int j = 0;  
        while (j < p.length()-1)  //循环里有++不能越界
        {  
            //k子串从头找匹配的,开始0、1
            if (k == -1 || p.charAt(j) == p.charAt(k))   
            {  
                ++k;  
                ++j;  
                next[j] = k;  //不匹配的其next[]设为0,对匹配的在其下一位的next[]设匹配个数
            }  
            else   
            {  
                k = next[k];  //对不匹配的数将k设-1
            }  
        } 
        return next;
    }
    
    public int[] GetNextval(String p){
        int[] next = new int[p.length()];
        next[0] = -1;  
        int k = -1;  
        int j = 0;  
        while (j < p.length()-1)  
        {  
            if (k == -1 || p.charAt(j) == p.charAt(k))   
            {  
                ++k;  
                ++j;  
                if (p.charAt(j) != p.charAt(k))  //对不一样的匹配还是原来的求法
                    next[j] = k;  
                else                      
                    next[j] = next[k];    //对子串中相同值next回溯
            }  
            else   
            {  
                k = next[k];  
            }  
        } 
        return next;
    }
    
    public void Print(int array[]){
        System.out.print("数组:\t");
        for(int i=0;i<array.length;i++){
            System.out.print(array[i]+"\t");
        }
        System.out.println("");
    }
    
    public int Search(String s,String p){
        this.next = GetNext(p);
        this.Print(this.next);
        this.next = GetNextval(p);
        this.Print(this.next);
        int i = 0;  
        int j = 0;   
        while (i < s.length() && j < p.length())  
        {    
            if (j == -1 || s.charAt(i) == p.charAt(j))  
            {  
                i++;  
                j++;  
            }  
            else  
            {       
                j = next[j];  
            }  
        }  
        if (j == p.length())  
            return i - j;  
        else  
            return -1;  
    }

    public static void main(String args[]){
        KMPTest ktest = new KMPTest();  
        int index = ktest.Search("BBC ABCDAB ABCDABCDABDE","ABCDABD");
        System.out.println(index);
    }
}
 

转载于:https://my.oschina.net/pumpkin724/blog/744414

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值