Longest Substring Without Repeating Characters
MediumSliding Window · Apple
Given a string s, find the longest substring (a contiguous run of characters) in which no character appears more than once, and return its length.
Characters are compared exactly: uppercase and lowercase letters are different, and spaces, digits, and symbols count as characters too. If s is empty, return 0.
Example 1
- Input:
- s = "abcaef"
- Output:
- 5
- Explanation
- Starting at index 0,
abcstops at the seconda. Starting one position later givesbcaef, five distinct characters, which is the longest.
Example 2
- Input:
- s = "abba"
- Output:
- 2
- Explanation
- The longest repeat-free substrings are
abandba, both of length 2. When the finalaarrives, the window must not jump back to before the secondb.
Example 3
- Input:
- s = ""
- Output:
- 0
- Explanation
- An empty string has no characters, so the answer is 0.
Constraints
- 0 ≤
s.length≤ 5 * 104 smay contain English letters, digits, symbols, and spaces