JAVA经典百题之计算字符串中子串出现的次数

程序分析

计算字符串中子串出现的次数,可以采用多种方法来实现。常见的方法包括暴力法、利用正则表达式和利用KMP算法。

方法一:暴力法

解题思路

  • 在主串中依次遍历每个位置,以该位置为起点,检查是否存在与子串相同的子串。
  • 比较简单直观,但时间复杂度较高。

实现代码

public class SubstringCount {
    public static int countSubstring(String str, String sub) {
        int count = 0;
        int len_str = str.length();
        int len_sub = sub.length();
        
        for (int i = 0; i <= len_str - len_sub; i++) {
            int j;
            for (j = 0; j < len_sub; j++) {
                if (str.charAt(i + j) != sub.charAt(j))
                    break;
            }
            if (j == len_sub)
                count++;
        }
        
        return count;
    }
    
    public static void main(String[] args) {
        String str = "ababababa";
        String sub = "aba";
        int result = countSubstring(str, sub);
        System.out.println("Number of occurrences: " + result);
    }
}

优缺点

  • 优点:实现简单,容易理解。
  • 缺点:时间复杂度高,O(n*m),其中n为主串长度,m为子串长度。

方法二:利用正则表达式

解题思路

  • 使用正则表达式的 Matcher 类来进行匹配,统计匹配次数。

实现代码

import java.util.regex.*;

public class SubstringCount {
    public static int countSubstring(String str, String sub) {
        Pattern pattern = Pattern.compile(sub);
        Matcher matcher = pattern.matcher(str);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }
    
    public static void main(String[] args) {
        String str = "ababababa";
        String sub = "aba";
        int result = countSubstring(str, sub);
        System.out.println("Number of occurrences: " + result);
    }
}

优缺点

  • 优点:实现简单,适用于简单的字符串匹配。
  • 缺点:性能可能较差,尤其是当主串和子串规模较大时。

方法三:KMP算法

解题思路

  • KMP算法利用了子串内部的信息,通过预处理生成一个部分匹配表,然后根据部分匹配表进行匹配,减少了不必要的比较。
  • 预处理过程时间复杂度为O(m),匹配过程时间复杂度为O(n+m),总体时间复杂度为O(n+m),其中n为主串长度,m为子串长度。

实现代码

public class SubstringCount {
    public static int[] computeLPSArray(String sub) {
        int len = sub.length();
        int[] lps = new int[len];
        int j = 0;
        int i = 1;
        
        while (i < len) {
            if (sub.charAt(i) == sub.charAt(j)) {
                j++;
                lps[i] = j;
                i++;
            } else {
                if (j != 0) {
                    j = lps[j - 1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }
    
    public static int countSubstring(String str, String sub) {
        int count = 0;
        int len_str = str.length();
        int len_sub = sub.length();
        int[] lps = computeLPSArray(sub);
        
        int j = 0;
        int i = 0;
        
        while (i < len_str) {
            if (sub.charAt(j) == str.charAt(i)) {
                j++;
                i++;
            }
            if (j == len_sub) {
                count++;
                j = lps[j - 1];
            } else if (i < len_str && sub.charAt(j) != str.charAt(i)) {
                if (j != 0) {
                    j = lps[j - 1];
                } else {
                    i++;
                }
            }
        }
        return count;
    }
    
    public static void main(String[] args) {
        String str = "ababababa";
        String sub = "aba";
        int result = countSubstring(str, sub);
        System.out.println("Number of occurrences: " + result);
    }
}

优缺点

  • 优点:时间复杂度较低,O(n+m),其中n为主串长度,m为子串长度。
  • 缺点:实现相对复杂,需要了解和实现KMP算法。

总结

  • 对于简单的需求或者规模较小的字符串,暴力法或者利用正则表达式都是不错的选择,简单易用。
  • 如果需要处理大规模字符串,特别是当子串较短时,推荐使用KMP算法,它可以显著提高匹配效率。
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高大人在上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值