1、方法功能描述
有序集合:(A、B、C、D、E、F、G、H、I、J),已經有分段(只有首尾):(A,D),(G、H)。
實現功能:找到其他的分段 (D、G)、(H、J)。
例如比賽軌道,從A地到J地,中間需要經過B、C、D、E、F、G、H、I、J,把軌道分為幾段(只有首尾):(A、D)、(D、G)、(G、H)、(H、J)。現在已經有分段(A、D)、(D、G),怎麼找到分段(G、H)、(H、J)?
2、代碼說明及描述
(1)思想
迴圈字串,逐個與子字串的第一個字元進行比對,
如果子字串列表中不存在,則添加子字串,並且把子字串的第一個字元設為該字串;
如果子字串中存在該字元,則取得子字串的最後一個字元,並且迴圈跳過該段。
(2)C#代碼
1 private List<List<string>> FillMidList(List<string> stringList, List<List<string>> midList)
2 {
3 List<List<string>> rtn = new List<List<string>>();
4 List<string> strList = null;//Char List
5 string start = string.Empty;//Start Char
6 string end = string.Empty;//End Char
7 bool isFind = false;
8 bool isFindEnd = false;//Find End Char
9
10 for (int i = 0; i < stringList.Count; i++)
11 {
12 start = stringList[i];
13 //If exit char
14 foreach (var item in midList)
15 {
16 if (start == item[0])
17 {
18 if (isFindEnd == true)
19 {
20 end = start;
21 }
22 isFind = true;
23 start = item[item.Count - 1];
24 break;
25 }
26 }
27
28 if (isFind == true)
29 {
30 isFind = false;
31 //Adjust index
32 for (int j = 0; j < stringList.Count; j++)
33 {
34 if (stringList[j] == start)
35 {
36 i = j - 1;
37 break;
38 }
39 }
40 if (isFindEnd == true)
41 {
42 strList.Add(end);
43 rtn.Add(strList);
44 isFindEnd = false;
45 end = string.Empty;
46 }
47 }
48 else
49 {
50 if (isFindEnd == true)
51 {
52 //Add the last
53 if (start == stringList[stringList.Count - 1])
54 {
55 strList.Add(start);
56 rtn.Add(strList);
57 }
58 }
59 else
60 {
61 strList = new List<string>();
62 strList.Add(start);
63 isFindEnd = true;
64 }
65 }
66 }
67
68 return rtn;
69 }
3、說明
這個功能在做項目的過程中有時會遇到,個人感覺寫的有點繁瑣,提供拙見供大家探討。