void BuildTree() { _Root = new SearchTree(); #region -Get Transions- foreach (ReplaceKeyValue rkv in _KeyValues) { SearchTree st = _Root; foreach (char c in rkv.Key) { SearchTree stNew = null; foreach (SearchTree s in st.Transitions) { if (s.Char == c) { stNew = s; break; } } if (stNew == null) { stNew = new SearchTree(st, c); st.AddTransition(stNew); } st = stNew; } st.AddResult(rkv); } #endregion #region -Find Failures- ArrayList nodes = new ArrayList(); foreach (SearchTree st in _Root.Transitions) { st.Failure = _Root; foreach (SearchTree trans in st.Transitions) { nodes.Add(trans); } } // 广度搜索算法(BFS) while (nodes.Count != 0) { ArrayList newNodes = new ArrayList(); foreach (SearchTree st in nodes) { SearchTree f = st.Parent.Failure; char c = st.Char; while (f != null && !f.Contains(c)) { f = f.Failure; } if (f == null) { st.Failure = _Root; } else { st.Failure = f.GetTransition(c); foreach (ReplaceKeyValue result in st.Failure.Results) { st.AddResult(result); } } foreach (SearchTree child in st.Transitions) { newNodes.Add(child); } } nodes = newNodes; } #endregion _Root.Failure = _Root; }