標籤:
假設有一個字串“abcdebfgh”
那麼最長不重複字串是"cdebfgh",長度是7
若是:abcdbefbghijij
應輸出:befbghij
|
以abcbef這個串為例 用一個資料結構pos記錄每個元素曾出現的下標,初始為-1 從s[0]開始,pos[‘a‘] == -1,說明a還未出現過,令pos[‘a‘] = 0,視為將a"加入當前串",同時間長度度++ 同理令pos[‘b‘] = 1,pos[‘c‘] = 2 到s[3]時,pos[‘b‘] != -1,說明‘b‘在前面已經出現過了,此時可得到一個不重複串"abc",重新整理當前的最大長度,然後做如下處理: pos[s[0~2]] = -1,亦即將"ab""移出當前串",同時當前長度減去3
重複以上過程 |
|
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication10{ class Program { static void Main(string[] args) { string ss = "abcdbefbghijij"; var list = ss.ToCharArray(); int left = 0; int right = 0; GetLen(list, out left, out right); Console.WriteLine(ss.Substring(left, right - left + 1)); } /// <summary> /// /// </summary> /// <param name="list"></param> /// <param name="left">right index from 0</param> /// <param name="right">right index from 0</param> /// <returns></returns> public static int GetLen(char[] list, out int left, out int right) { if (list == null || list.Length <= 0) { throw new Exception("the input list length is 0"); } int len = list.Length; left = 0; right = 0; int maxLen = 0; int start = 0; int tempMaxLen = 0; Dictionary<char, int> cache = new Dictionary<char, int>(); for (int i = 0; i < len; i++) { if (!cache.Keys.Contains(list[i]) || cache[list[i]]==-1) //這個建不存在或者有建,但是值為-1,表明這個字元還沒出現過. { tempMaxLen++; cache.Add(list[i], i); } else { //there is duplicated char abcdbefgh if (tempMaxLen > maxLen) { maxLen = tempMaxLen; left = start; right = i - 1; } tempMaxLen = i - cache[list[i]]; for (int j = start; j < cache[list[i]]; j++) // 注意:網上好多例子是清楚這個cache裡所有的,應該是錯誤的;僅僅應該清楚上次重複字元前面的字元。 { cache[list[j]] = -1; } start = cache[list[i]] + 1; cache[list[i]] = i; } } if (tempMaxLen > maxLen) { maxLen = tempMaxLen; left = start; right = len-1; } return maxLen; } }}
網上有些例子有問題,所以重新寫了下 求字串的最長不重複字串