再度提升!.NET脏字过滤算法
点击次数:17 次 发布日期:2008-11-26 22:30:08 作者:源代码网
|
源代码网推荐 源代码网推荐 直接贴出全部代码了,通过新增的一个byte[char.MaxValue]和BitArray(char.MaxValue),减少了大量的Substring和GetHashCode的调用。耗的内存也不算多,除HashSet外,仅需要144k内存。 源代码网推荐 源代码网推荐 引用此文或者使用此代码请说明出处,谢谢,以便于我将来的更新。 源代码网推荐 源代码网推荐 public class BadWordsFilter 源代码网推荐 { 源代码网推荐 private HashSet<string> hash = new HashSet<string>(); 源代码网推荐 private byte[] fastCheck = new byte[char.MaxValue]; 源代码网推荐 private byte[] fastLength = new byte[char.MaxValue]; 源代码网推荐 private BitArray charCheck = new BitArray(char.MaxValue); 源代码网推荐 private BitArray endCheck = new BitArray(char.MaxValue); 源代码网推荐 private int maxWordLength = 0; 源代码网推荐 private int minWordLength = int.MaxValue; 源代码网推荐 源代码网推荐 public BadWordsFilter() 源代码网推荐 { 源代码网推荐 源代码网推荐 } 源代码网推荐 源代码网推荐 public void Init(string[] badwords) 源代码网推荐 { 源代码网推荐 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 源代码网推荐 { 源代码网推荐 fastLength[word[0]] |= (byte)(1 << (Math.Min(7, word.Length - 2))); 源代码网推荐 endCheck[word[word.Length - 1]] = true; 源代码网推荐 源代码网推荐 hash.Add(word); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 public string Filter(string text, string mask) 源代码网推荐 { 源代码网推荐 throw new NotImplementedException(); 源代码网推荐 } 源代码网推荐 源代码网推荐 public bool HasBadWord(string text) 源代码网推荐 { 源代码网推荐 int index = 0; 源代码网推荐 源代码网推荐 while (index < text.Length) 源代码网推荐 { 源代码网推荐 int count = 1; 源代码网推荐 源代码网推荐 if (index > 0 || (fastCheck[text[index]] & 1) == 0) 源代码网推荐 { 源代码网推荐 while (index < text.Length - 1 && (fastCheck[text[++index]] & 1) == 0) ; 源代码网推荐 } 源代码网推荐 源代码网推荐 char begin = text[index]; 源代码网推荐 源代码网推荐 if (minWordLength == 1 && charCheck[begin]) 源代码网推荐 { 源代码网推荐 return true; 源代码网推荐 } 源代码网推荐 源代码网推荐 for (int j = 1; j <= Math.Min(maxWordLength, text.Length - index - 1); j++) 源代码网推荐 { 源代码网推荐 char current = text[index + j]; 源代码网推荐 源代码网推荐 if ((fastCheck[current] & 1) == 0) 源代码网推荐 { 源代码网推荐 ++count; 源代码网推荐 } 源代码网推荐 源代码网推荐 if ((fastCheck[current] & (1 << Math.Min(j, 7))) == 0) 源代码网推荐 { 源代码网推荐 break; 源代码网推荐 } 源代码网推荐 源代码网推荐 if (j + 1 >= minWordLength) 源代码网推荐 { 源代码网推荐 if ((fastLength[begin] & (1 << Math.Min(j - 1, 7))) > 0 && endCheck[current]) 源代码网推荐 { 源代码网推荐 string sub = text.Substring(index, j + 1); 源代码网推荐 源代码网推荐 if (hash.Contains(sub)) 源代码网推荐 { 源代码网推荐 return true; 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 index += count; 源代码网推荐 } 源代码网推荐 源代码网推荐 return false; 源代码网推荐 } 源代码网推荐 } 做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。 源代码网推荐 源代码网供稿. |
