public void Match(string text) { // text是主串 int n = text.Length; var p = Root; for (int i = 0; i < n; ++i) { var str = text[i]; while (p.Children.GetValueOrDefault(str) == null && p != Root) { p = p.Fail; // 失败指针发挥作用的地方 } p = p.Children.GetValueOrDefault(str); if (p == null) { p = Root; // 如果没有匹配的,从root开始重新匹配 } AcAutomatonNode tmp = p; while (tmp != Root) { // 打印出可以匹配的模式串 if (tmp.IsFind == true) { int pos = i - tmp.Length + 1; Console.WriteLine("匹配起始下标" + pos + "; 长度" + tmp.Length); } tmp = tmp.Fail; } } }
public AcAutomatonTrie() { Root = new AcAutomatonNode(char.MinValue, 0); }