KMP算法代码实现记录
2021-05-11 14:29
                         标签:int   table   相等   字符   构建   记录   算法   length   tab      KMP算法代码实现记录 标签:int   table   相等   字符   构建   记录   算法   length   tab    原文地址:https://www.cnblogs.com/ningxinjie/p/13151779.htmlprivate static int kmpDemo(String str1,String str2){
        if (str2==null||str1==null||str1.length()-str2.length()){
            return -1;
        }
        //首先构建字符匹配表
        int[] matchTable=getStrMatchTable(str2);
        int fatherP=0,childP=0;
        while (fatherP
            //直接移动到子串当前匹配的长度-字符匹配表中对应的当前未匹配的索引的值
                    fatherP+=childP+1-matchTable[childP];
                }
            }else {
                fatherP++;
            }
        }
        return -1;
    }
    //构建字符匹配表
    private static int[] getStrMatchTable(String str){
        int[] res=new int[str.length()];
        res[0]=0;
        for (int i = 1,j=0; i ) {
            //当str.charAt(i) != str.charAt(j),需要从res[j-1]获取新的j的位置
            //知道找到二者相等时才退出寻找
            //这是kmp算法的核心
            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j=res[j-1];
            }
            //当str.charAt(i)==str.charAt(j)满足时,部分匹配值就+
            if(str.charAt(i)==str.charAt(j)){
                j++;
            }
            res[i]=j;
        }
        return res;
    }