|
| 1 | +# Longest Substring Without Repeating Characters |
| 2 | + |
| 3 | +Given a string s, find the length of the longest substring without repeating characters. |
| 4 | + |
| 5 | +## Examples |
| 6 | + |
| 7 | +Example 1: |
| 8 | + |
| 9 | +Input: s = "abcabcbb" |
| 10 | +Output: 3 |
| 11 | +Explanation: The answer is "abc", with the length of 3. |
| 12 | +Example 2: |
| 13 | + |
| 14 | +Input: s = "bbbbb" |
| 15 | +Output: 1 |
| 16 | +Explanation: The answer is "b", with the length of 1. |
| 17 | +Example 3: |
| 18 | + |
| 19 | +Input: s = "pwwkew" |
| 20 | +Output: 3 |
| 21 | +Explanation: The answer is "wke", with the length of 3. |
| 22 | +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. |
| 23 | +Example 4: |
| 24 | + |
| 25 | +Input: s = "" |
| 26 | +Output: 0 |
| 27 | + |
| 28 | +## Solution |
| 29 | + |
| 30 | +This solution uses a variable-length sliding window to consider all substrings without repeating characters, and returns |
| 31 | +the length of the longest one at the end. |
| 32 | +We represent the state of the current window with a dictionary state which maps each character to the number of times it |
| 33 | +appears in the window. |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +We use a for-loop to increment end to repeatedly expand the window. Each time we expand the window, we first increment |
| 39 | +the count of s[end] in state. As long as the character at end is not a duplicate character in the window, we can compare |
| 40 | +the length of the current window to the longest window we've seen so far, and continue expanding. The character at end |
| 41 | +is a duplicate if state[s[end]] > 1. |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +At this point, we have to contract the window because it contains more than one g. We do this by removing the leftmost |
| 52 | +character (start += 1) from the window, and decrementing its count in state until there is only one g left in the window. |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +At this point, our window is valid again, and we can continue this process of expanding and contracting the window until |
| 58 | +end reaches the end of the string. |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
0 commit comments