字符串匹配算法(一)BF算法、RK算法

BF算法

算法详解

  • BF算法也就是Brute Force 算法,中文叫暴力匹配算法,也叫朴素匹配算法。
  • 模式串和主串:例如:我们在字符串A中查找字符串B,那么字符串A就是主串,字符串B就是模式串。
  • 主要思路:我们在主串中,检查其实位置分别是0 ~ n-m(n是主串A的长度,m是模式串B的长度)且长度为m的n-m+1个字串,看有没有跟模式串匹配的。
    在这里插入图片描述

算法实现

package com.xxliao.algorithms.string_match.brute_force;

/**
 * @author xxliao
 * @description: BF算法 - 暴力匹配算法
 * @date 2024/5/31 12:56
 */
public class BruteForceMatch {

    public static void main(String[] args) {
        System.out.println(match("ccaaac","caaac"));
    }


    /**
     * @description  字符串匹配,暴力匹配
     * main:主串
     * sub: 模式串
     * @author  xxliao
     * @date  2024/5/31 12:57
     */
    public static boolean match(String main,String pattern) {
        char[] mainChars = main.toCharArray();
        char[] patternChars = pattern.toCharArray();
        // 遍历主串,然后循环内部遍历模式串,进行比对
        for(int i = 0; i <= main.length()- pattern.length(); i++) {
            boolean flag = true;
            int temp = i;
            for (int j = 0; j < pattern.length(); j++) {
                if(mainChars[temp++] != patternChars[j]) {
                    flag = false;
                }
            }
            if(flag)
                return true;
        }
        return false;
    }

}

演示结果:
在这里插入图片描述

RK算法

算法详解

  • RK算法也就是Rabin-Karp算法,RK的算法思路是:通过哈希算法对主串的n-m+1个字符串(n是主串的长度,m是模式串的长度)分别求出哈希值,然后逐个与模式串的哈希值比较大小,如果哈希值相等,则就说明对应的字串与模式串匹配成功(不考虑哈希冲突,或者哈希值匹配成功之后,然后再比对一下具体的值是否相等)。

算法实现

package com.xxliao.algorithms.string_match.hash;

/**
 * @author xxliao
 * @description: 字符串匹配 RK算法,hash匹配
 * @date 2024/5/31 13:59
 */
public class HashMatch {

    public static void main(String[] args) {
        System.out.println(match("abcvdcd","vdcd"));
    }

    /**
     * @description  字符串hash 匹配
     * @author  xxliao
     * @date  2024/5/31 14:00
     */
    public static boolean match(String main, String pattern) {
        int hash_pattern = hash(pattern);
        for (int i = 0; i <= (main.length() - pattern.length()); i++) {
            // 主串截串后与子串的hash值比较
            if (hash_pattern==hash(main.substring(i, i + pattern.length()))) {
                return true;
            }
        }
        return false;
    }

    /**
     * @description  求出字符串的hash值,这里简单实现,实际业务没这么简单
     * @author  xxliao
     * @date  2024/5/31 14:01
     */
    public static int hash(String src) {
        int hash = 0;
        for (int i = 0; i < src.length(); i++) {
            hash *= 26;
            hash += src.charAt(i) - 97;
        }
        return hash;
    }
}

演示结果:
在这里插入图片描述

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

骑车上酒吧

帮到了您,有闲钱,再打赏哦~

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

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

打赏作者

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

抵扣说明:

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

余额充值