组合算法纠错(高分)
问题描述:http://topic.csdn.net/u/20110615/10/a913bb78-3303-46fb-bc47-820f7489cb40.html
算法初稿(存在问题,请纠错,高分答谢):
C# code
算法初稿(存在问题,请纠错,高分答谢):
C# code
public static string Translate(string type, string str) { StringBuilder sb = new StringBuilder(); IList<int> typeList = AnalyzeType(type); foreach (int numType in typeList) { BuildResult(numType, AnalyzeStr(str), sb); } return sb.ToString(); } public static IList<int> AnalyzeType(string type) { IList<int> typeList = new List<int>(); Regex reg = new Regex(@"^\d{1}$"); Array arr = type.ToArray(); foreach (var character in arr) { if (reg.IsMatch(character.ToString())) { typeList.Add(int.Parse(character.ToString())); } } return typeList; } public static IList<string> AnalyzeStr(string str) { IList<string> list = new List<string>(); Regex reg = new Regex(@"^\d{6}$"); string[] content = str.Split(','); foreach (string everyStr in content) { if (reg.IsMatch(everyStr)) { list.Add(everyStr); } } return list; } public static void BuildResult(int type, IList<string> contentList, StringBuilder sb) { if (contentList.Count != 0) { string code = contentList.First(); contentList.Remove(code); Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>(); for (int j = 1; j < type; j++) { string[] list = new string[contentList.Count]; contentList.CopyTo(list, 0); List<string> copyList = list.ToList<string>(); dictionary.Add(j, copyList); } while (dictionary.Values.Last().Count > 0) { bool addInsb = false; StringBuilder newSb = new StringBuilder(); newSb.Append("+").Append(code); foreach (List<string> list in dictionary.Values) { if (list != null && list.Count > 0) { string listFir = list.First(); //前3位相同的则为一组 if (!list.First().Substring(0, 3).Equals(code.Substring(0, 3))) { newSb.Append("+").Append(list.First()); addInsb = true; } foreach (List<string> listA in dictionary.Values) { listA.Remove(listFir); } } if (!addInsb) break; } newSb.Append("|"); if (addInsb) { sb.Append(newSb); } //因为移出了每次的第一个,必须使得循环从头开始 BuildResult(type, contentList, sb); } } }
作者: hacker_hyj 发布时间: 2011-06-16
看了一下原帖,发现用个2重循环就可以,只要保证每个元素只同后面组的元素组合就可以了。
作者: litaoye 发布时间: 2011-06-16