[LeetCode] - Longest Substring Without Repeating Characters
題目:找出最長的不重複子字串
My Solution
1 static int LengthOfLongestSubstring(string s) { 2 if (string.IsNullOrEmpty(s)) return 0; 3 if (s.Length == 1) return 1; 4 5 List<char> charCounter = new List<char>(); 6 List<int> len = new List<int>(); 7 for (int i = 0, j = 0; i < s.Length && j < s.Length ;) { 8 //子串遇到重複的,移除掉開頭那個重複的字 9 if(charCounter.Contains(s[j]) == true) { 10 charCounter.Remove(s[i]); 11 //i往前移動,下一輪字串 12 //遇到重複時,i到j-1為不重複字串,i+1到j-1也必為不重複字串,所以從i+1到j開始比對,只需要移動i 13 i++; 14 } else { 15 //沒有重複就不斷把字加進去做比對重複之用 16 charCounter.Add(s[j]); 17 //j往前移動,直到遇到重複或結束 18 j++; 19 } 20 //取該次不重複的長度 21 len.Add(j - i); 22 } 23 24 return len.Max(); 25 }
流程
個人解法,研究別人更好的解法中,請參考。