我们网站的脏字字典中大概有600多个词,而且会发生变化,因此简单的在数据新增/修改的时候做一次脏字过滤是不够的。在网站从.NET 1.1到2.0改版的时候,对新版的测试发现旧的脏字过滤算法耗费的时间过长,需要做一些优化。
算法的关键,还是使用空间来换时间,使用了2个全局的BitArray, 长度均为Char.MaxValue。其中一个BitArray用来判断是否有某个char开头的脏字,另一个BitArray用来判断所有脏字中是否包含某个char。经过这两个BitArray,可以做出快速判断,之后就使用Hash Code来判断完整的脏字,通过预先获取的最大脏字长度优化遍历过程。
需要的变量如下:
private Dictionary<string, object> hash = new Dictionary<string, object>();
private BitArray firstCharCheck = new BitArray(char.MaxValue);
private BitArray allCharCheck = new BitArray(char.MaxValue);
private int maxLength = 0;
其中hash只使用到了key,value都置为null。也可以使用.NET 3.5中的HashSet,或者使用Dictionary<string, int>,记录脏字的出现次数。
初始化这些数据的方法如下:
foreach (string word in badwords)
{
if (!hash.ContainsKey(word))
{
hash.Add(word, null);
maxlength = Math.Max(maxlength, word.Length);
firstCharCheck[word[0]] = true;
foreach (char c in word)
{
allCharCheck[c] = true;
}
}
}
判断脏字是否出现在一个字符串中的代码如下:
int index = 0;
int offset = 0;
while (index < text.Length)
{
if (!firstCharCheck[text[index]])
{
while (index < text.Length - 1 && !firstCharCheck[text[++index]]) ;
}
for (int j = 1; j <= Math.Min(maxlength, text.Length - index); j++)
{
if (!allCharCheck[text[index + j - 1]])
{
break;
}
string sub = text.Substring(index, j);
if (hash.ContainsKey(sub))
{
return true;
}
}
index++;
}
return false;
替换的代码就不贴了,跟判断包含类似,只不过不能发现一个脏字后就退出循环。如果出现脏字的可能不是很高,就没有必要创建一个临时的StringBuilder。
进一步,可以通过借鉴.NET源码中string.GetHashCode()的实现,避免一次Substring的调用,提高性能。也可以设计递进的HashCode实现,比如"helloworld"可以用"helloworl"的hash进一步计算,优化效率。
另外,也可以抛弃Hash,改用排序过的string[],用BinarySearch来判断sub是否为脏字。BinarySearch的结果是可以递进的,即可以用查找"helloworl"的结果来加速判断"helloworld"。 (已测试,700个脏字,BinarySearch的效率有时会低很多。)
本文作者:xingd 来源: http://www.cnblogs.com/xingd/archive/2008/01/23/1050443.html
CIO之家 www.ciozj.com 微信公众号:imciow