c# – 所有匹配的Boyer-Moore-Horspool算法(在字节数组中查找字节数组)

前端之家收集整理的这篇文章主要介绍了c# – 所有匹配的Boyer-Moore-Horspool算法(在字节数组中查找字节数组)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我对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;
}

我试图修改它以返回所有匹配而不是仅返回第一个索引,但我到处都得到IndexOutOfRangeException 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;
}
原文链接:https://www.f2er.com/csharp/244366.html

猜你在找的C#相关文章