Longest Substring without Repeating Characters
Concepts
- Hash map / Hash set
Sliding Window
initialize hash map, start, end, and answer
loop through such that start and end are both not passing the string's length
- if the hash map does not contain the last checked character:
- mark it as checked
- increment end
- if end - start is greater than the current answer
- make end - start the new current answer
- else
- mark the hash map containing the current character at start as true
- increment start
- if the hash map does not contain the last checked character:
Things to Note:
- The algorithm will keep iterating the start until we are at the last point we saw the end character. This is important to note because we are unsetting every character before the character matching the end character. This is the back part of the sliding window. It will continue to slide up until the new substring is set. This new substring will only be set as the new one if end - start is greater than the previously saved answer.
int longestSubString(string str)
{
bool charMap[128];
int start = 0, end = 0, ans = 0;
while( start < str.length() && end < str.length()) {
if(charMap[str[end]] == false) {
charMap[str[end]] = true;
end++;
ans = max(ans, end - start);
}
else {
charMap[s[start]] = false;
start++;
}
}
return ans;
}
Complexity
Space: 128 bools, 3 ints
Time: O(2n) = O(n)