首页 > 编程语言 > 详细

KMP算法代码实现记录

时间:2020-06-17 13:04:43      阅读:74      评论:0      收藏:0      [点我收藏+]
private static int kmpDemo(String str1,String str2){
        if (str2==null||str1==null||str1.length()-str2.length()<0){
            return -1;
        }
        //首先构建字符匹配表
        int[] matchTable=getStrMatchTable(str2);
        int fatherP=0,childP=0;
        while (fatherP<str1.length()&&childP<str2.length()){
            childP=0;
            if(str1.charAt(fatherP)==str2.charAt(childP)){
                while (fatherP<str1.length()&&childP<str2.length()&&str1.charAt(fatherP)==str2.charAt(childP)){
                    fatherP++;
                    childP++;
                }
                if(childP==str2.length()){
                    return fatherP-str2.length();
                }else {
            //直接移动到子串当前匹配的长度-字符匹配表中对应的当前未匹配的索引的值 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 < res.length; 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; }

 

KMP算法代码实现记录

原文:https://www.cnblogs.com/ningxinjie/p/13151779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!