boyer-moore算法python

Boyer-Moore算法是一种用于字符串搜索的高效算法,它通过跳过尽可能多的字符来减少比较的次数。下面是一个简单的Python实现Boyer-Moore算法的示例:

def build_bad_char_table(pattern):

    bad_char_table = {}

    pattern_length = len(pattern)

    for i in range(pattern_length - 1):

        bad_char_table[pattern[i]] = pattern_length - i - 1

    return bad_char_table

def build_good_suffix_table(pattern):

    pattern_length = len(pattern)

    good_suffix_table = [-1] * pattern_length

    last_prefix_position = pattern_length

    for i in range(pattern_length - 1, -1, -1):

        if is_prefix(pattern, i + 1):

            last_prefix_position = i + 1

        good_suffix_table[i] = last_prefix_position + pattern_length - i - 1

    for i in range(pattern_length - 1):

        j = pattern_length - 1 - i

        if is_suffix(pattern, j):

            last_prefix_position = j

        good_suffix_table[j] = min(good_suffix_table[j], pattern_length - 1 - last_prefix_position + j)

    return good_suffix_table

def is_prefix(pattern, p):

    pattern_length = len(pattern)

    j = 0

    for i in range(p, pattern_length):

        if pattern[i] != pattern[j]:

            return False

        j += 1

    return True

def is_suffix(pattern, p):

    pattern_length = len(pattern)

    i = 0

    j = p

    while j < pattern_length:

        if pattern[i] != pattern[j]:

            return False

        i += 1

        j += 1

    return True

def boyer_moore_search(text, pattern):

    bad_char_table = build_bad_char_table(pattern)

    good_suffix_table = build_good_suffix_table(pattern)

    pattern_length = len(pattern)

    text_length = len(text)

    i = 0

    while i <= text_length - pattern_length:

        j = pattern_length - 1

        while j >= 0 and pattern[j] == text[i + j]:

            j -= 1

        if j < 0:

            # Pattern found at index i

            print("Pattern found at index", i)

            i += good_suffix_table[0]

        else:

            # Shift based on the bad character rule and good suffix rule

            bad_char_shift = bad_char_table.get(text[i + j, -1])

            good_suffix_shift = good_suffix_table[j]

            i += max(bad_char_shift, good_suffix_shift)

# 测试Boyer-Moore搜索

text = "This is a sample text for testing the Boyer-Moore algorithm."

pattern = "Boyer-Moore"

boyer_moore_search(text, pattern)

这个示例包含了Boyer-Moore算法的实现,包括构建坏字符表(bad character table)和好后缀表(good suffix table)。然后,boyer_moore_search函数使用这些表来执行搜索。在这个示例中,它会输出找到的模式的索引位置。你可以将text和pattern更改为你自己的文本和模式来测试不同的输入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南抖北快东卫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值