Given a string, find the length of the longest substring without repeating characters.
| Input | Output | Longest substring |
|---|---|---|
"abcdabcbd" | 4 | "abcd" |
"aaaaaa" | 1 | "a" |
"tidddosa" | 4 | "dosa" |
"au" | 2 | "au" |
Solution
We can solve this in O(n) using a sliding window. The l and r are the left and right indices of the window, respectively. We start with l and r at 0, representing a window one item wide and then move r to the right item by item. We check the set to see if we've seen the item before and if so we get the size of the window (r - l) and update longest if applicable. When we find an item we've already seen we remove the character at position l and move it the right, continuing until we remove the item at r from the set. We then start again.
use HashSet;
use max;
LeetCode says...
Runtime: 4 ms, faster than 76.05% of Rust online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 2.1 MB, less than 100.00% of Rust online submissions for Longest Substring Without Repeating Characters.
Not the fastest implementation, but I think it's easy to understand. I'd be interested to see what others have done to make it faster, so ping me on social media if you've got a faster solution.