Boyer-Moore 可能是已知最快的非索引文本搜索算法。所以我在 C# 中为我的Black Belt Coder网站实现它。
我让它工作了,与String.IndexOf()
. 但是,当我将StringComparison.Ordinal
参数添加到 时IndexOf
,它开始优于我的 Boyer-Moore 实现。有时,数量相当可观。
我想知道是否有人可以帮助我找出原因。我明白为什么StringComparision.Ordinal
会加快速度,但它怎么能比 Boyer-Moore 更快呢?是因为 .NET 平台本身的开销,可能是因为必须验证数组索引以确保它们在范围内,或者完全是其他原因。某些算法在 C#.NET 中不实用吗?
下面是关键代码。
// Base for search classes
abstract class SearchBase
{
public const int InvalidIndex = -1;
protected string _pattern;
public SearchBase(string pattern) { _pattern = pattern; }
public abstract int Search(string text, int startIndex);
public int Search(string text) { return Search(text, 0); }
}
/// <summary>
/// A simplified Boyer-Moore implementation.
///
/// Note: Uses a single skip array, which uses more memory than needed and
/// may not be large enough. Will be replaced with multi-stage table.
/// </summary>
class BoyerMoore2 : SearchBase
{
private byte[] _skipArray;
public BoyerMoore2(string pattern)
: base(pattern)
{
// TODO: To be replaced with multi-stage table
_skipArray = new byte[0x10000];
for (int i = 0; i < _skipArray.Length; i++)
_skipArray[i] = (byte)_pattern.Length;
for (int i = 0; i < _pattern.Length - 1; i++)
_skipArray[_pattern[i]] = (byte)(_pattern.Length - i - 1);
}
public override int Search(string text, int startIndex)
{
int i = startIndex;
// Loop while there's still room for search term
while (i <= (text.Length - _pattern.Length))
{
// Look if we have a match at this position
int j = _pattern.Length - 1;
while (j >= 0 && _pattern[j] == text[i + j])
j--;
if (j < 0)
{
// Match found
return i;
}
// Advance to next comparision
i += Math.Max(_skipArray[text[i + j]] - _pattern.Length + 1 + j, 1);
}
// No match found
return InvalidIndex;
}
}
编辑:我已经在http://www.blackbeltcoder.com/Articles/algorithms/fast-text-search-with-boyer-moore上发布了我所有的测试代码和结论。