KMP匹配算法实现

包含匹配算法和获取next数组的方法

class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.isEmpty()) return 0;
        int i=-1,j=-1;
        int m=haystack.length();
        int n=needle.length();
        int[] next=getNext(needle); 
        while(i<m&&j<n){
            if(j==-1||(haystack.charAt(i)==needle.charAt(j))){
                i++;
                j++;
            }else{
                j=next[j];
            }
        }
        if(j>n-1){
            return i-j;
        }
        return -1;
    }
    private int[] getNext(String str){
        int[] next=new int[str.length()];
        int i=0,j=-1;
        next[0]=-1;
        while(i<str.length()-1){
            if(j==-1||str.charAt(i)==str.charAt(j)){
                i++;
                j++;
                next[i]=j;
            }else{
                j=next[j];
            }
        }
        return next;
    }
}

猜你喜欢

转载自blog.csdn.net/orangefly0214/article/details/89857350