本文介绍了所有匹配的 Boyer-Moore-Horspool 算法(在 Byte 数组中查找 Byte 数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我对 BMH 算法的实现(它就像一个魅力):

Here is my implementation of BMH algorithm (it works like a charm):

public static Int64 IndexOf(this Byte[] value, Byte[] pattern)
{
    if (value == null)
        throw new ArgumentNullException("value");

    if (pattern == null)
        throw new ArgumentNullException("pattern");

    Int64 valueLength = value.LongLength;
    Int64 patternLength = pattern.LongLength;

    if ((valueLength == 0) || (patternLength == 0) || (patternLength > valueLength))
        return -1;

    Int64[] badCharacters = new Int64[256];

    for (Int64 i = 0; i < 256; ++i)
        badCharacters[i] = patternLength;

    Int64 lastPatternByte = patternLength - 1;

    for (Int64 i = 0; i < lastPatternByte; ++i)
        badCharacters[pattern[i]] = lastPatternByte - i;

    // Beginning

    Int64 index = 0;

    while (index <= (valueLength - patternLength))
    {
        for (Int64 i = lastPatternByte; value[(index + i)] == pattern[i]; --i)
        {
            if (i == 0)
                return index;
        }

        index += badCharacters[value[(index + lastPatternByte)]];
    }

    return -1;
}

我试图修改它以返回所有匹配项而不是仅返回第一个索引,但我在任何地方都收到 IndexOutOfRangeException D:

I tried to modify it in order to return all the matches instead of only the first index, but I'm getting IndexOutOfRangeException everywhere D:

显然我遗漏了一些重要的东西,或者我没有正确理解它是如何工作的.我做错了什么?

Obviously I'm missing something important or I didn't properly understood how it works. What am I doing wrong?

public static List<Int64> IndexesOf(this Byte[] value, Byte[] pattern)
{
    if (value == null)
        throw new ArgumentNullException("value");

    if (pattern == null)
        throw new ArgumentNullException("pattern");

    Int64 valueLength = value.LongLength;
    Int64 patternLength = pattern.LongLength;

    if ((valueLength == 0) || (patternLength == 0) || (patternLength > valueLength))
        return (new List<Int64>());

    Int64[] badCharacters = new Int64[256];

    for (Int64 i = 0; i < 256; ++i)
        badCharacters[i] = patternLength;

    Int64 lastPatternByte = patternLength - 1;

    for (Int64 i = 0; i < lastPatternByte; ++i)
        badCharacters[pattern[i]] = lastPatternByte - i;

    // Beginning

    Int64 index = 0;
    List<Int64> indexes = new List<Int64>();

    while (index <= (valueLength - patternLength))
    {
        for (Int64 i = lastPatternByte; value[(index + i)] == pattern[i]; --i)
        {
            if (i == 0)
                indexes.Add(index);
        }

        index += badCharacters[value[(index + lastPatternByte)]];
    }

    return indexes;
}

推荐答案

更改

if (i == 0)
    indexes.Add(index);

if (i == 0)
{
    indexes.Add(index);
    break;
}

这篇关于所有匹配的 Boyer-Moore-Horspool 算法(在 Byte 数组中查找 Byte 数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 20:54