【数据结构】手撕串的模式匹配算法

本文介绍了三种模式匹配算法:使用String内置方法实现的模式匹配、朴素的模式匹配和KMP模式匹配算法。文中详细展示了每种算法的实现代码,并对比了它们的时间复杂度,分别为O(mn)和更高效的O(m+n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 使用String内置的方法实现模式匹配【时间复杂度O(m×(n−m+1))≈O(mn)O(m\times(n-m+1))\approx O(mn)O(m×(nm+1))O(mn)】:

    public static int index(String str, String find) {
        String sub;
        for (int i = 0; i <= str.length() - find.length(); ++i) {
            sub = str.substring(i, i + find.length());
            if (find.compareTo(sub) == 0) return i;
        }
        return -1;
    }
    
  2. 朴素的模式匹配算法【时间复杂度O(m×(n−m+1))≈O(mn)O(m\times(n-m+1))\approx O(mn)O(m×(nm+1))O(mn)】:

    public static int index(String str, String find) {
        int k = 0;
        int i = 0, j = 0;
    
        while (i < str.length() && j < find.length()) {
            if (str.charAt(i) == find.charAt(j)) {
                ++i;
                ++j;
            } else {
                ++k;
                i = k;
                j = 0;
            }
        }
    
        if (j == find.length()) return k;
        return -1;
    }
    
  3. KMP模式匹配算法【时间复杂度O(m+n)O(m+n)O(m+n)】:

    public static int index(String str, String find) {
        // 计算模式串的next数组
        int next[] = new int[find.length()];
        int m = 0, n = -1; // 错位
        next[0] = -1;
        while (m < find.length() - 1) {
            if (n == -1 || find.charAt(m) == find.charAt(n)) {
                ++m;
                ++n;
                next[m] = n;
            }
            else
                n = next[n];
        }
    
        // 开始匹配
        int i = 0, j = 0;
        while (i < str.length() && j < find.length()) {
            if (j == -1 || str.charAt(i) == find.charAt(j)) {
                ++i;
                ++j;
            } else
                j = next[j];
        }
    
        if (j == find.length()) return i - find.length();
        return -1;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值