(再发).NET脏字过滤算法
点击次数:29 次 发布日期:2008-11-26 22:30:10 作者:源代码网
|
源代码网推荐 源代码网推荐 感谢sumtech的回复和讨论,原本的效率已经足够网站实用了,虽然也想到一些改进方法,但是一直懒得去做。sumtech通过邮件跟我讨论,我也终于抽了时间做了改进,改进后的算法效率比原先的算法提高了400%,也就是仅需要原来的1/5时间。 源代码网推荐 源代码网推荐 算法关键是将两个BitArray合并成了byte[char.MaxValue],其中7个bit用来判断前7个字符,另一个bit判断其他字符。并且增加了minWordLength和charCheck,用来过滤过短的判断,以及仅有一个字符时的快速判断。 源代码网推荐 源代码网推荐 使用的数据: 源代码网推荐 源代码网推荐 private HashSet<string> hash = new HashSet<string>(); 源代码网推荐 private byte[] fastCheck = new byte[char.MaxValue]; 源代码网推荐 private BitArray charCheck = new BitArray(char.MaxValue); 源代码网推荐 private int maxWordLength = 0; 源代码网推荐 private int minWordLength = int.MaxValue; 源代码网推荐 初始化数据的代码: 源代码网推荐 源代码网推荐 foreach (string word in badwords) 源代码网推荐 { 源代码网推荐 maxWordLength = Math.Max(maxWordLength, word.Length); 源代码网推荐 minWordLength = Math.Min(minWordLength, word.Length); 源代码网推荐 源代码网推荐 for (int i = 0; i < 7 && i < word.Length; i++) 源代码网推荐 { 源代码网推荐 fastCheck[word[i]] |= (byte)(1 << i); 源代码网推荐 } 源代码网推荐 源代码网推荐 for (int i = 7; i < word.Length; i++) 源代码网推荐 { 源代码网推荐 fastCheck[word[i]] |= 0x80; 源代码网推荐 } 源代码网推荐 源代码网推荐 if (word.Length == 1) 源代码网推荐 { 源代码网推荐 charCheck[word[0]] = true; 源代码网推荐 } 源代码网推荐 else 源代码网推荐 { 源代码网推荐 hash.Add(word); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 判断是否包含脏字的代码: 源代码网推荐 源代码网推荐 int index = 0; 源代码网推荐 源代码网推荐 while (index < text.Length) 源代码网推荐 { 源代码网推荐 if ((fastCheck[text[index]] & 1) == 0) 源代码网推荐 { 源代码网推荐 while (index < text.Length - 1 && (fastCheck[text[++index]] & 1) == 0) ; 源代码网推荐 } 源代码网推荐 源代码网推荐 for (int j = 1; j <= Math.Min(maxWordLength, text.Length - index - 1); j++) 源代码网推荐 { 源代码网推荐 if ((fastCheck[text[index + j]] & (1 << Math.Min(j, 7))) == 0) 源代码网推荐 { 源代码网推荐 break; 源代码网推荐 } 源代码网推荐 源代码网推荐 if (j >= minWordLength) 源代码网推荐 { 源代码网推荐 if (j == 1) 源代码网推荐 { 源代码网推荐 if (charCheck[text[index]]) 源代码网推荐 { 源代码网推荐 return true; 源代码网推荐 } 源代码网推荐 } 源代码网推荐 else 源代码网推荐 { 源代码网推荐 string sub = text.Substring(index, j + 1); 源代码网推荐 源代码网推荐 if (hash.Contains(sub)) 源代码网推荐 { 源代码网推荐 return true; 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 index++; 源代码网推荐 } 源代码网推荐 源代码网推荐 return false; 源代码网推荐 最后介绍下自己,我现任大众点评网(dianping.com)的系统架构师,自己的个人博客是www.stevenxu.com,点评网的整个开发团队即将推出团队博客,我的一些文章一般会先发到博客园和团队博客,跟据反馈修订后再发到个人博客。 源代码网推荐 做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。 源代码网推荐 源代码网供稿. |
