方法分享:有序集合分段

來源:互聯網
上載者:User

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、說明

  這個功能在做項目的過程中有時會遇到,個人感覺寫的有點繁瑣,提供拙見供大家探討。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.