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

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;
}

我试图对其进行修改,以便返回所有匹配项而不是仅返回第一个索引,但是我到处都是D:

显然,我缺少重要的东西,或者我没有正确理解它的工作原理。我究竟做错了什么?
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;
}

关于c# - 所有匹配项的Boyer-Moore-Horspool算法(在Byte数组内部查找Byte数组),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16252518/

10-13 06:56