日期:2014-05-20 浏览次数:20866 次
class DictGen { class Node { public Dictionary<char, Node> Dict { get; set; } public Node() { Dict = new Dictionary<char, Node>(); } public IEnumerable<string> Get() { foreach (var item in Dict.OrderBy(x => x.Key)) { if (item.Key == '\0') yield return ""; foreach (var item1 in item.Value.Get()) { yield return item.Key.ToString().ToLower() + item1; } } } } public static IEnumerable<string> ParseString(TextReader tr) { Node rootNode = new Node(); Node currNode = rootNode; int state = 0; char[] arr; try { while (true) { arr = tr.ReadLine().ToUpper().ToCharArray(); for (int i = 0; i < arr.GetLength(0); i++) { if (arr[i] >= 65 && arr[i] <= 90) { state = 1; if (!currNode.Dict.ContainsKey(arr[i])) currNode.Dict.Add(arr[i], new Node()); currNode = currNode.Dict[arr[i]]; } else { if (state == 1) { if (!currNode.Dict.ContainsKey('\0')) currNode.Dict.Add('\0', new Node()); state = 0; } currNode = rootNode; } } } } catch { } return rootNode.Get(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { foreach (var item in GetStr("Hello World! Hello everyone, my name is caozhy!")) { Console.WriteLine(item); } } static IEnumerable<string> GetStr(string str) { string[] list = str.Split(new char[] { ' ', ',', '!' }, StringSplitOptions.RemoveEmptyEntries); return list.Distinct().OrderBy(i => i.ToLowerInvariant()).AsEnumerable(); } } }
------解决方案--------------------
这种问题我一般用c++使用STL的map,直接put,然后使用iterator输出。
O(nlogn)
------解决方案--------------------
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { foreach (var item in GetStr("Hello World! Hello everyone, my name is caozhy!,ni ,hao ,....")) { Console.WriteLine(item); } } static IEnumerable<string> GetStr(string str) { Regex re = new Regex(@"[a-zA-Z]+"); List<string> list = new List<string>(); MatchCollection mc = re.Matches(str); foreach (Match item in mc) { list.Add(item.Value); } return list.Distinct().OrderBy(i => i.ToLowerInvariant()).AsEnumerable(); } } }