private static void ExactMatch(string text, int idx, PYNode node, PYResultNode res_node) { if (idx == text.Length) { return; // match finished } var c = text[idx++]; PYNode subnode; if (!node.children.TryGetValue(c, out subnode)) { return; // match failed } if (subnode.IsLeaf) { res_node.children[idx] = new PYResultNode(idx) { parent = res_node } } ; if (subnode.children == null) { return; // match finished } ExactMatch(text, idx, subnode, res_node); }
/// <summary> /// 猜测拼音 /// </summary> /// <param name="text">必须是小写</param> /// <returns></returns> public static List <string> GuessPYs(string text) { var root_resultnode = new PYResultNode(0); // root of result node var queue = new Queue <PYResultNode>(); queue.Enqueue(root_resultnode); var validLeaves = new List <PYResultNode>(); var pys = new List <string>(); while (queue.Count > 0) { var res_node = queue.Dequeue(); if (res_node.start < text.Length) { ExactMatch(text, res_node.start, _root, res_node); if (res_node.children.Count > 0) { foreach (var p in res_node.children) { queue.Enqueue(p.Value); } } } else // res_node.start == text.Length denotes it is a valid leaf { validLeaves.Add(res_node); } } // 从根节点到叶节点的路径表示一种拼音划分方法,但是需要去掉不完整的划分方法(视为无效) for (int i = 0; i < validLeaves.Count; i++) { var rn = validLeaves[i].parent; var origin_chars = text.ToCharArray(); while (rn != null) { origin_chars[rn.start] = (char)(origin_chars[rn.start] - 32); rn = rn.parent; } pys.Add(new string(origin_chars)); } return(pys); }