3 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given"abcabcbb"
, the answer is"abc"
, which the length is 3.
Given"bbbbb"
, the answer is"b"
, with the length of 1.
Given"pwwkew"
, the answer is"wke"
, with the length of 3. Note that the answer must be asubstring,"pwke"
is asubsequence and not a substring.
The Idea: The basic idea is to maintain two pointers. One left, and one right, both of which begin at 0. These left and right pointers are going maintain the current substring and hence also represent their length. Additionally, use a hash table to store the previous instance of a character. Move forward with the right iterator until we encounter a duplicate character (which can be identified through the hash table). When we encounter a a duplicate, move the left pointer so that we have no duplicates. We can use the hash table to identify where that previous duplicate character was. Moving the left point + 1 past this position will may ensure that the substring does not have any duplicates. The is one more thing. Consider the string abba
. When we encounter the last a, our left pointer will point to index 1 since character a was duplicated. However, because we have moved the left pointer to index 2 after first having identified the duplicate of b, the first is become irrelevant. In other words, the left pointer can only move forwards in order to account for old history changes.
Complexity: O(n) time and space.
Python
Last updated