字符串匹配问题——KMP算法

目录

KMP算法介绍

KMP算法最佳应用-字符串匹配问题

思路分析图解

KMP字符串匹配代码实现:


KMP算法介绍

1) KMP是一个解决模式串在文本串是否出现过,如果出现过,最早出现的位置的经典算法

2) KMP方法算法就利用之前判断过信息,通过一个next数组,保存模式串中前后最长公共子序列的长度,保持i 不回溯,通过next数组修改j 的位置,让子串尽量地移动到有效的位置,进行匹配。

3)参考资料: https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html

KMP算法最佳应用-字符串匹配问题

字符串匹配问题: :

1)有一个字符串str1= "BBC ABCDAB ABCDABCDABDE",和一个子串str2="ABCDABD"

2)现在要判断strl是否含有str2,如果存在,就返回第一次出现的位置,如果没有,则返回-1

3)要求:使用KMP算法完成判断

思路分析图解

 

KMP字符串匹配代码实现:

public class ViolenceMatch {
    public static void main(String[] args) {//字符串匹配算法

        String str1 = "安全出口 出口安全 安全安全出口安安安安全全出口出口 ";
        String str2 = "安全出口安安";
        //测试KMP算法
        int[] next = KmpNext(str2);
        System.out.println(Arrays.toString(next));//[0, 0, 0, 0, 1, 1]
        int index2 = KmpSearch(str1, str2, next);
        System.out.println("KMP算法:index=" + index2);
    }

    /**
     * kmp算法实现
     *
     * @param str1 源字符串
     * @param str2 子串
     * @param next 部分匹配表,是子串对应的部分匹配表
     * @return 找到则返回最开始的索引位置,否则返回-1
     */

    public static int KmpSearch(String str1, String str2, int[] next) {
        //遍历
        for (int i = 0, j = 0; i < str1.length(); i++) {
            //需要处理str1.charAt(i)!=str2.charAt(j),去调整j的大小
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {//找到了
                return i - j + 1;
            }
        }
        return -1;//没找到
    }

    //获取到一个字符串[子串]的部分匹配表
    public static int[] KmpNext(String dest) {
        //创建一个next数组保存部分匹配值
        int[] next = new int[dest.length()];
        next[0] = 0;//如果字符串长度为1,部分匹配值就是0
        for (int i = 1, j = 0; i < dest.length(); i++) {
            //当dest.charAt(i)!=dest.charAt(j),我们需要从next[j-1]种获取新的j
            //直到我们发现有dest.charAt(j)成立才退出
            //这是kmp算法的核心点
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            //当dest.charAt(i)==dest.charAt(j)满足时,部分匹配值就是+1
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_52729352/article/details/121948650