題目:Longest Substring Without Repeating Characters
難度:Medium
技巧在於使用 Sliding Window 去解,左右指標會一直移動,直到遍歷整個字串,即左右指標重疊。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class Solution { public int LengthOfLongestSubstring(string s) { if (s.Length == 0) { return 0; }
IDictionary<char, int> dict = new Dictionary<char, int>(); int left = 0; int right = 0; int maxLength = 0;
while (left < s.Length && right < s.Length) { char c = s[right];
if (dict.ContainsKey(c)) { left = Math.Max(dict[c] + 1, left); } dict[c] = right;
maxLength = Math.Max(maxLength, right - left + 1);
right += 1; }
return maxLength; } }
|
參考
演算法筆記系列 — Two Pointer 與 Sliding Window
YouTube: Longest Substring Without Repeating Characters